2009-04-24 4 views
1

オブジェクトのプロパティを印刷できますが、iListsのネストされたコレクションをヒットすると、Genericsを使用したリフレクション:ネストされたIListsのコレクションの問題

foreach (PropertyInformation p in properties) 
      { 
       //Ensure IList type, then perform recursive call 
       if (p.PropertyType.IsGenericType) 
       { 
         // recursive call to PrintListProperties<p.type?>((IList)p,"  "); 
       } 

誰でも助けてください。

乾杯

KA

答えて

3

私はここで声をかけています。その後

private void PrintListProperties(IList list, Type type) 
{ 
    //reflect over type and use that when enumerating the list 
} 

、ネストされたリストに遭遇したときに、このような何か:たぶん、あなたはこのようになります非ジェネリックPrintListPropertiesメソッドを持つことができます再び

if (p.PropertyType.IsGenericType) 
{ 
    PringListProperties((Ilist)p,p.PropertyType.GetGenericArguments()[0]); 
} 

を、テストしていませんこれは、しかし

+1

+1。関数の型を使って何かをやっていない限り、汎用である必要はありません。あなたがしているのが反射検査であれば、このようにTypeインスタンスを渡すことができます。 –

2
p.PropertyType.GetGenericArguments() 

はあなたの型引数の配列を与えます。 (この場合、1つの要素で、IList<T>のT)

+1

彼の問題は、彼の現在の機能(PrintListPropertiesを呼び出している...それに旋回を与えます0)の型ではなく、型のインスタンスを持ちます。 –

3
foreach (PropertyInfo p in props) 
    { 
     // We need to distinguish between indexed properties and parameterless properties 
     if (p.GetIndexParameters().Length == 0) 
     { 
      // This is the value of the property 
      Object v = p.GetValue(t, null); 
      // If it implements IList<> ... 
      if (v != null && v.GetType().GetInterface("IList`1") != null) 
      { 
       // ... then make the recursive call: 
       typeof(YourDeclaringClassHere).GetMethod("PrintListProperties").MakeGenericMethod(v.GetType().GetInterface("IList`1").GetGenericArguments()).Invoke(null, new object[] { v, indent + " " }); 
      } 
      Console.WriteLine(indent + " {0} = {1}", p.Name, v); 
     } 
     else 
     { 
      Console.WriteLine(indent + " {0} = <indexed property>", p.Name); 
     } 
    }  
0
var dataType = myInstance.GetType(); 
var allProperties = dataType.GetProperties(BindingFlags.Public | BindingFlags.Instance); 
var listProperties = 
    allProperties. 
    Where(prop => prop.PropertyType.GetInterfaces(). 
     Any(i => i == typeof(IList))); 
関連する問題