不使用AutoMapper...(因为负责此项目的某人会看到依赖项而感到惊恐)
我有一个类(A类)具有任意数量的属性。我有另一个类(B类),具有相同的属性(相同的名称和类型)。Class B也可以有其他不相关的变量。
是否有一些简单的反射代码可以将值从A类复制到B类?
越简单越好。
不使用AutoMapper...(因为负责此项目的某人会看到依赖项而感到惊恐)
我有一个类(A类)具有任意数量的属性。我有另一个类(B类),具有相同的属性(相同的名称和类型)。Class B也可以有其他不相关的变量。
是否有一些简单的反射代码可以将值从A类复制到B类?
越简单越好。
Type typeB = b.GetType();
foreach (PropertyInfo property in a.GetType().GetProperties())
{
if (!property.CanRead || (property.GetIndexParameters().Length > 0))
continue;
PropertyInfo other = typeB.GetProperty(property.Name);
if ((other != null) && (other.CanWrite))
other.SetValue(b, property.GetValue(a, null), null);
}
这个?
static void Copy(object a, object b)
{
foreach (PropertyInfo propA in a.GetType().GetProperties())
{
PropertyInfo propB = b.GetType().GetProperty(propA.Name);
propB.SetValue(b, propA.GetValue(a, null), null);
}
}
public static Action<TIn, TOut> GetMapper<TIn, TOut>()
{
var aProperties = typeof(TIn).GetProperties();
var bType = typeof (TOut);
var result = from aProperty in aProperties
let bProperty = bType.GetProperty(aProperty.Name)
where bProperty != null &&
aProperty.CanRead &&
bProperty.CanWrite
select new {
aGetter = aProperty.GetGetMethod(),
bSetter = bProperty.GetSetMethod()
};
return (a, b) =>
{
foreach (var properties in result)
{
var propertyValue = properties.aGetter.Invoke(a, null);
properties.bSetter.Invoke(b, new[] { propertyValue });
}
};
}
我知道你要求反射代码,这是一个旧帖子,但我有一个不同的建议想要分享。它可能比反射更快。
您可以将输入对象序列化为JSON字符串,然后反序列化为输出对象。所有具有相同名称的属性都将自动分配给新对象的属性。
var json = JsonConvert.SerializeObject(a);
var b = JsonConvert.DeserializeObject<T>(json);
试试这个:
PropertyInfo[] aProps = typeof(A).GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Default | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);
PropertyInfo[] bProps = typeof(B).GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Default | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);
foreach (PropertyInfo pi in aProps)
{
PropertyInfo infoObj = bProps.Where(info => info.Name == pi.Name).First();
if (infoObj != null)
{
infoObj.SetValue(second, pi.GetValue(first, null), null);
}
}