如果我做这样的事情:
var a = new List<something>();
var b = new something();
a.Add(b);
var c = a[0].GetType();
Run Code Online (Sandbox Code Playgroud)
C持有我想要的类型(这是"某事").如果不创建列表,你怎么能得到"东西"的类型?
在这种情况下,您可以说,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];
}
Run Code Online (Sandbox Code Playgroud)
如果你正在寻找Tin中IList<T>它变得复杂,因为你实际上可以有一个声明类型的类型class FooBar: IList<Foo>, IList<Bar>.这就是为什么最后一个函数提供了几种不同的可能性.如果你想在模棱两可的情况下抛出异常,请选择第一种可能性.如果您只想选择任意一个,请选择第二个.如果你关心你得到哪一个,你将不得不做更多的编码,以某种方式选择哪一个最符合你的需求.