2011-09-24 68 views
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对象是“空”。我只是想将它初始化为一些值。

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

编辑:

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

我需要初始化所有“的ComplexType”成员在“数据”到“复杂类型”

+0

你想达到的究竟是什么?你到目前为止尝试过什么? – DeCaf

+0

@DeCaf:请检查编辑。 –

回答

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

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