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

Iss*_*ram 6 .net c# reflection c#-3.0 c#-4.0

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

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

是否有一些简单的反射代码可以将值从A类复制到B类?

越简单越好.

Jan*_*Vos 22

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);
}
Run Code Online (Sandbox Code Playgroud)