<分区>
如果我这样做:
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 包含我想要的类型(即“某物”)。在不创建列表的情况下如何获得“某物”的类型?
最佳答案
在这种情况下,您可以说 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];
}
如果您正在寻找 T
在IList<T>
它变得复杂,因为您实际上可以声明一个类型,如 class FooBar: IList<Foo>, IList<Bar>
.这就是为什么最后一个函数提供了几种不同的可能性。如果您希望在出现歧义的情况下抛出异常,请选择第一种可能性。如果您只想随意选择一个,请选择第二个。如果您关心获得的是哪一个,则必须进行更多编码才能以某种方式选择最能满足您需求的一个。
关于C# 获取类型() : Code how to get the type of T in List<T> without actual elements?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4039179/