BITKit/Src/Core/AutoMapper/BITMapper.cs

30 lines
1.0 KiB
C#
Raw Normal View History

2023-06-29 14:57:11 +08:00
namespace BITKit
2023-06-05 19:57:17 +08:00
{
public static class BITMapper
{
2024-11-03 16:38:17 +08:00
public static T Map<T>(object source, T target) where T : class
2023-06-05 19:57:17 +08:00
{
2024-07-29 14:56:29 +08:00
foreach (var info in source.GetType().GetProperties(ReflectionHelper.Flags))
2023-06-05 19:57:17 +08:00
{
2024-07-29 14:56:29 +08:00
if (info.CanWrite is false) continue;
var targetInfo = target.GetType().GetProperty(info.Name, ReflectionHelper.Flags);
2024-08-08 23:07:50 +08:00
var value = info.GetValue(source);
if (value is not null)
{
targetInfo?.SetValue(target,value );
}
2023-06-05 19:57:17 +08:00
}
2024-07-29 14:56:29 +08:00
foreach (var info in source.GetType().GetFields(ReflectionHelper.Flags))
2023-06-05 19:57:17 +08:00
{
2024-07-29 14:56:29 +08:00
var targetInfo = target.GetType().GetField(info.Name, ReflectionHelper.Flags);
2024-08-08 23:07:50 +08:00
var value = info.GetValue(source);
if (value is not null)
{
targetInfo?.SetValue(target, value);
}
2023-06-05 19:57:17 +08:00
}
2024-11-03 16:38:17 +08:00
return target;
2023-06-05 19:57:17 +08:00
}
}
}