2011-09-24 66 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(...)來檢索)。

請注意,雖然反射不是特別有效。