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。
我很確定它可以完成,如果你知道如何做,我會非常感激,如果你能與我分享你的知識!
好的,謝謝,方法調用它是那麼 – 2009-02-17 11:35:13