获取从List< T>派生的List中的元素类型.在C#中 [英] Get type of elements in a List derived from List<T> in C#

查看:56
本文介绍了获取从List< T>派生的List中的元素类型.在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一些类是从 List< T> 派生的:

Lets say that I have classes which derive from List<T>:

public class StringList : List<String> {}
public class NameList : StringList {}

public class IntList : List<int> {}

现在,我有一个通用方法,期望使用类型 List< T> :

Now I have a generic method which expects type List<T>:

public static Method<T>() { ... }

如何确定此方法中列表中包含的元素的类型,即如何在派生类中获取通用参数类型?

How can I determine the type of elements contained in a list in this method, i.e. how to get the generic argument type in a derived class?

对于基类,我可以调用 typeof(T> .GetGenericArguments(),但是对于派生类,它返回零大小.

For base class I can call typeof(T>.GetGenericArguments(), but for derived class it returns zero size.

PS:在我的具体情况下,该方法期望的类型并非完全是 List< T> ,而是 IList .

PS: In my concrete situation the type which method expects is not exactly List<T>, but IList.

推荐答案

您可以编写如下方法:

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];
}

请注意,您需要在此处进行适当的完整性检查(而不是 FirstOrDefault()和0索引编制)

Note that you'll need appropriate sanity checks here (rather than FirstOrDefault() and 0 indexing)

这篇关于获取从List&lt; T&gt;派生的List中的元素类型.在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆