两个对象属性值想同会赋值
using System.Reflection;
public static void AutoMap(object source, object destination)
{
var sourceProperties = source.GetType().GetProperties();
var destinationProperties = destination.GetType().GetProperties();
foreach (var prop in sourceProperties)
{
var matchingProp = destinationProperties.FirstOrDefault(p => p.Name == prop.Name && p.PropertyType == prop.PropertyType);
if (matchingProp != null && matchingProp.CanWrite)
{
var value = prop.GetValue(source);
if (value == null && matchingProp.PropertyType.IsValueType)
{
// 对于值类型,需要特殊处理,例如使用默认(T)来获取默认值
value = Activator.CreateInstance(matchingProp.PropertyType);
}
matchingProp.SetValue(destination, value);
}
}
}