如何从其基础对象填充对象的属性值

时间:2014-02-07 08:44:17

标签: c# properties populate

我有一个名为BaseClass的类,它有许多不同类型的属性,包括列表和字典。该类有三个派生类,其中包含更多属性。这些类已经在大型应用程序中使用,因此目前无法改变设计。

所以派生类就像:

public class DerivedClass1 : BaseClass
{
    public string PropertyOne { get; set; }
}

public class DerivedClass2 : BaseClass
{
    public string PropertyTwo { get; set; }
}

public class DerivedClass3 : BaseClass
{
    public string PropertyThree { get; set; }
}

当我根据驻留在基类中的属性对这些类进行反序列化时,我需要执行多态。所以每次将Json对象反序列化为BaseClass时,我需要检查该属性值并创建正确的具体类。要做到这一点,我需要一个像PopulateFrom(这个BaseClass实例,BaseClass fromObject)的方法,所以我可以这样称呼它:

var deserializedObjet = Serializer.Deserialize(jsonString);
switch(deserializedObjet.ConcreteType)
{
    case 1:
      return new DerivedClass1().PopulateFrom(deserializedObjet );
     case 2: 
      return new DerivedClass2().PopulateFrom(deserializedObjet );
     case 3: 
      return new DerivedClass3().PopulateFrom(deserializedObjet );
}

派生类在Json字符串中没有数据。他们所做的是他们获得相同的数据,但他们对它们执行不同的操作,或者他们以不同的方式表示它们,所以我只需要将Json反序列化为BaseClass。

我知道StackTrace.Text有一个类似的方法,但是从版本4开始添加了这个方法,这个方法不是免费的。

1 个答案:

答案 0 :(得分:0)

您可以创建必需的类实例,将属性值从当前基本实例复制到新创建的具有反射的实例。请在下面找到示例(必须在编译之前修复)

static void PopulateFrom(this BaseClass dest, BaseClass source) //extension method will not modify legacy code and can be added to the any static class
{
     var properties = source.GetType().GetProperties(public only);
     foreach (var pi in properties)
        if (pi.CanRead && pi.CanWrite)
          pi.SetValue(dest, pi.GetValue(source, null), null); //this will work only for classes inherited from BaseClass
}

此外,您可以覆盖BaseClass中的赋值运算符并使用它复制属性值。