检查通用类型

Tar*_*her 3 c# generics

我想检查泛型变量是否属于某种类型,但不想检查通用部分.

假设我有一个变量List<int>和另一个变量List<double>.我只想检查它是否是类型List<>

if(variable is List) {}
Run Code Online (Sandbox Code Playgroud)

并不是

if (variable is List<int> || variable is List<double>) {}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

谢谢

Meh*_*ari 9

variable.GetType().IsGenericType && 
            variable.GetType().GetGenericTypeDefinition() == typeof(List<>)
Run Code Online (Sandbox Code Playgroud)

当然,这仅在变量属于类型List<T>且不是派生类时才有效.如果要检查它是List<T>继承还是继承,则应遍历继承层次结构并检查每个基类的上述语句:

static bool IsList(object obj)
{
    Type t = obj.GetType();
    do {
        if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
            return true;
        t = t.BaseType;
    } while (t != null);
    return false;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 6

您可以通过反射测试确切的类型:

    object list = new List<int>();

    Type type = list.GetType();
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
    {
        Console.WriteLine("is a List-of-" + type.GetGenericArguments()[0].Name);
    }
Run Code Online (Sandbox Code Playgroud)

就个人而言,我会寻找IList<T>- 比混凝土更通用List<T>:

    foreach (Type interfaceType in type.GetInterfaces())
    {
        if (interfaceType.IsGenericType
            && interfaceType.GetGenericTypeDefinition()
            == typeof(IList<>))
        {
            Console.WriteLine("Is an IList-of-" +
                interfaceType.GetGenericArguments()[0].Name);
        }
    }
Run Code Online (Sandbox Code Playgroud)


Luk*_*keH 5

Type t = variable.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)