[英]Get type of elements in a List derived from List<T> in C#
Lets say that I have classes which derive from List<T>
: 可以说我有一些从
List<T>
派生的类:
public class StringList : List<String> {}
public class NameList : StringList {}
public class IntList : List<int> {}
Now I have a generic method which expects type List<T>
: 现在,我有一个通用方法,期望使用类型
List<T>
:
public static Method<T>() { ... }
How can I determine the type of elements contained in a list in this method, ie how to get the generic argument type in a derived class? 如何确定此方法中列表中包含的元素的类型,即如何在派生类中获取通用参数类型?
For base class I can call typeof(T>.GetGenericArguments()
, but for derived class it returns zero size. 对于基类,我可以调用
typeof(T>.GetGenericArguments()
,但是对于派生类,它返回零大小。
PS: In my concrete situation the type which method expects is not exactly List<T>
, but IList
. PS:在我的具体情况下,方法期望的类型不完全是
List<T>
,而是IList
。
You can write the method like this: 您可以这样编写方法:
public static void Method<T>(List<T> thing) (or IList<T>)
{
//Here, `T` is the type of the elements in the list
}
Of if you need a reflection-based check: 如果您需要基于反射的检查:
public static void Method(Type myType)
{
var thing = myType.GetInterfaces()
.Where(i => i.IsGenericType)
.Where(i => i.GetGenericTypeDefinition() == typeof(IList<>))
.FirstOrDefault()
.GetGenericArguments()[0];
}
Note that you'll need appropriate sanity checks here (rather than FirstOrDefault()
and 0 indexing) 请注意,您将需要在此处进行适当的完整性检查(而不是
FirstOrDefault()
和0索引FirstOrDefault()
)
If you want both the type of the list and the element type of the list at compile time, your Method
must have two generic definitions like this: 如果在编译时同时需要列表的类型和列表的元素类型,则
Method
必须具有两个通用定义,如下所示:
public static void Method<T, E>(T list) where T : List<E>
{
// example1
// T is List<int> and E is int
// example2
// T is NameList and E is String
}
Method<List<int>, int>(new List<int>()); //example1
Method<NameList, string>(new NameList()); //example2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.