2009-02-17 59 views
1

的通用對象我有一些簡單的代碼這說明我的問題:上溯造型到從System.Object

private void InitializeOther() 
{ 
    List<Foo> list = new List<Foo>(); 
    Casting(list); 
} 

//in the "real" case I have no knowledge of o, other than it could be a List<> 
private void Casting(object o) 
{ 
    Type t = o.GetType(); 
    while (t.BaseType != typeof(Object)) 
    { 
    if (t.IsGenericType && typeof(List<>) == t.GetGenericTypeDefinition()) 
    { 
     //now I know that o is of type List<>. How can I now access List<> members from o? 
     break; 
    } 
    t = t.BaseType; 
    } 
} 

所以,我可以肯定的是對象o是(或派生)從List<T>,但現在我希望能夠在o上訪問List<T>成員,這意味着將其最高可達List<Foo>。在我的「真實」情況下,我不瞭解Foo。

我很確定它可以完成,如果你知道如何做,我會非常感激,如果你能與我分享你的知識!

回答

0

由於List<T>實現了泛型接口和非泛型接口,因此一個小小的破解將試圖將o轉換爲非泛型的IListCollection<T>也是一樣,這是用戶集合最常用的基類。

如果這不是一個選項,你可以隨時與反射方法調用(後期綁定)相處:MethodInfo.Invoke()

+0

好的,謝謝,方法調用它是那麼 – 2009-02-17 11:35:13