【发布时间】:2010-10-28 02:07:08
【问题描述】:
如果我这样做:
var a = new List<something>();
var b = new something();
a.Add(b);
var c = a[0].GetType();
C 包含我想要的类型(即“某物”)。在不创建列表的情况下如何获得“某物”的类型?
【问题讨论】:
标签: c# reflection
如果我这样做:
var a = new List<something>();
var b = new something();
a.Add(b);
var c = a[0].GetType();
C 包含我想要的类型(即“某物”)。在不创建列表的情况下如何获得“某物”的类型?
【问题讨论】:
标签: c# reflection
在这种情况下,您可以直接说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];
}
如果您在IList<T> 中寻找T,它会变得复杂,因为您实际上可以声明像class FooBar: IList<Foo>, IList<Bar> 这样的类型。这就是为什么最后一个函数提供了几种不同的可能性。如果您想在有歧义的情况下抛出异常,请选择第一种可能性。如果您只想选择任意一个,请选择第二个。如果你关心你得到哪一个,你将不得不做更多的编码来以某种方式选择哪一个最能满足你的需求。
【讨论】:
IList<T>,你应该使用我回答中的最后一个示例。
试试:
Type type = a.GetType().GetGenericArguments()[0];
【讨论】:
使用typeof 运算符,例如typeof(T) 或 typeof(something)。
【讨论】: