本文介绍了相同的变量名 - 2个不同的类别 - 如何复制值从一个到另一个 - 反思 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果不使用AutoMapper ......(因为有人负责这个项目将狗屁砖时,他们看到的依赖)

我有一个类(A类)与然而,许多性能。我有另一个类(B类)与相同的属性(相同的名称和类型)。 B类也可能有其他与联合国有关的变量。

有一些简单的反射code可从A类值复制到B级?

越简单越好。

解决方案

 键入的TypeB = b.GetType();
的foreach(的PropertyInfo财产a.GetType()。GetProperties中())
{
    如果(property.CanRead ||(property.GetIndexParameters()长度>!0))
        继续;

    的PropertyInfo其他= typeB.GetProperty(property.Name);
    如果((其它= NULL)及!及(other.CanWrite))
        other.SetValue(B,property.GetValue(一,空),空);
}
 

Without using AutoMapper... (because someone in charge of this project will shit bricks when they see dependencies)

I have a class (class A) with however many properties. I have another class (class B) with those same properties (same names and type). Class B could also have other un related variables.

Is there some simple reflection code that can copy values from class A to class B?

The simpler the better.

解决方案
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);
}

这篇关于相同的变量名 - 2个不同的类别 - 如何复制值从一个到另一个 - 反思 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:36