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



代码树如下:

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'

如果我理解正确的话,也许这样做会奏效:

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(...)检索)。

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

相关内容

  • 没有找到相关文章

最新更新