2010-10-28 42 views

回答

7

在這種情況下,你只能說var c = typeof(something);,但在一般情況下,你可以使用這個:

Type c = a.GetType().GetGenericArguments()[0];

更具體地講,也有可能是4種不同的情況:

void func1(List<something> arg) 
{ 
    Type t = typeof(something); 
} 

void func2<T>(List<T> arg) 
{ 
    Type t = typeof(T); 
} 

void func3(object arg) 
{ 
    // assuming arg is a List<T> 
    Type t = arg.GetType().GetGenericArguments()[0]; 
} 

void func4(object arg) 
{ 
    // assuming arg is an IList<T> 
    Type t; 

    // this assumes that arg implements exactly 1 IList<> interface; 
    // if not it throws an exception indicating that IList<> is ambiguous 
    t = arg.GetType().GetInterface(typeof(IList<>).Name).GetGenericArguments()[0]; 

    // if you expect multiple instances of IList<>, it gets more complicated; 
    // we'll take just the first one we find 
    t = arg.GetType().GetInterfaces().Where(
     i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>)) 
     .First().GetGenericArguments()[0]; 
} 

如果您正在尋找TIList<T>,它會變得非常複雜,因爲您實際上可能有一種類型被宣告爲class FooBar: IList<Foo>, IList<Bar>。這就是爲什麼最後一個功能有兩種不同的可能性。如果你想要在模棱兩可的情況下拋出一個異常,那就去第一種可能性。如果你只是想選擇任意一個,那就去第二個。如果你關心你得到哪一個,你將不得不做更多的編碼,以某種方式選擇哪一個最能滿足你的需求。

+0

這比50行代碼我在另一個問題看見好十倍。簡單是更好的時候它的工作;) – 2010-10-28 02:14:59

+0

什麼其他問題有50行代碼? – Gabe 2010-10-28 02:16:13

+0

Zim博士:如果它實際上可能是IList ',你應該在我的答案中使用最後一個樣本。 – Gabe 2010-10-28 02:26:09

1

使用typeof運算符,例如, typeof(T)typeof(something)

+0

你會怎麼做typeof(IList )並得到某種類型的東西? – 2010-10-28 02:15:56

+0

@Dr。 Zim見Gabe的回答。 – 2010-10-28 02:28:05

2

嘗試:

Type type = a.GetType().GetGenericArguments()[0];

相關問題