假设我有派生自 List<T>
的类:
public class StringList : List<String> {}
public class NameList : StringList {}
public class IntList : List<int> {}
现在我有一个需要类型 List<T>
的通用方法:
public static Method<T>() { ... }
如何确定此方法中列表中包含的元素类型,即如何获取派生类中的泛型参数类型?
对于基类,我可以调用 typeof(T>.GetGenericArguments()
,但对于派生类,它返回零大小。
PS:在我的具体情况下,方法期望的类型不完全是 List<T>
,但是IList
.
最佳答案
你可以这样写方法:
public static void Method<T>(List<T> thing) (or IList<T>)
{
//Here, `T` is the type of the elements in the list
}
如果您需要基于反射的检查:
public static void Method(Type myType)
{
var thing = myType.GetInterfaces()
.Where(i => i.IsGenericType)
.Where(i => i.GetGenericTypeDefinition() == typeof(IList<>))
.FirstOrDefault()
.GetGenericArguments()[0];
}
请注意,您需要在此处进行适当的完整性检查(而不是 FirstOrDefault()
和 0 索引)
关于c# - 获取从 C# 中的 List<T> 派生的列表中的元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41234210/