使用Reflection初始化嵌套的复杂类型

时间:2011-09-24 11:22:09

标签: c# reflection .net-2.0

代码树就像:

Class Data
{
    List<Primitive> obj;
}

Class A: Primitive
{
    ComplexType CTA;
}

Class B: A
{
    ComplexType CTB;
    Z o;
}

Class Z
{
   ComplexType CTZ;
}

Class ComplexType { .... }

现在在List<Primitive> obj中,有许多类ComplexType对象为'null'。我只想将其初始化为某种值。

问题是如何使用反射遍历整个树。

修改:

Data data = GetData(); //All members of type ComplexType are null. 
ComplexType complexType = GetComplexType();

我需要将'data'中的所有'ComplexType'成员初始化为'complexType'

1 个答案:

答案 0 :(得分:2)

如果我理解正确,或许这样的事情可以解决问题:

static void AssignAllComplexTypeMembers(object instance, ComplexType value)
{
     // If instance itself is null it has no members to which we can assign a value
     if (instance != null)
     {
        // Get all fields that are non-static in the instance provided...
        FieldInfo[] fields = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

        foreach (FieldInfo field in fields)
        {
           if (field.FieldType == typeof(ComplexType))
           {
              // If field is of type ComplexType we assign the provided value to it.
              field.SetValue(instance, value);
           }
           else if (field.FieldType.IsClass)
           {
              // Otherwise, if the type of the field is a class recursively do this assignment 
              // on the instance contained in that field. (If null this method will perform no action on it)
              AssignAllComplexTypeMembers(field.GetValue(instance), value);
           }
        }
     }
  }

这个方法将被称为:

foreach (var instance in data.obj)
        AssignAllComplexTypeMembers(instance, t);

此代码当然仅适用于字段。如果你想要属性,你必须让循环遍历所有属性(可以通过instance.GetType().GetProperties(...)进行检索)。

请注意,但反射并不是特别有效。