相同的变量名称 – 2个不同的类 – 如何将值从一个复制到另一个 – reflection – C#

不使用AutoMapper …(因为当他们看到依赖项时,负责这个项目的人会打砖块)

我有一个类(A类),但有很多属性。 我有另一个类(B类)具有相同的属性(相同的名称和类型)。 B类也可能有其他无关的变量。

是否有一些简单的reflection代码可以将值从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 GetMapper() { 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 }); } }; } 

试试这个:-

 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); } } 

我知道你要求reflection代码,这是一个旧post,但我有一个不同的建议,并希望分享它。 它可能比reflection更快。

您可以将输入对象序列化为json字符串,然后反序列化为输出对象。 具有相同名称的所有属性将自动分配给新对象的属性。

 var json = JsonConvert.SerializeObject(a); var b = JsonConvert.DeserializeObject(json);