将 IsAssignableFrom 与“开放"泛型类型一起使用 [英] Using IsAssignableFrom with 'open' generic types

查看:38
本文介绍了将 IsAssignableFrom 与“开放"泛型类型一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用反射,我试图找到从给定基类继承的类型集.很快就找到了简单的类型,但我对泛型感到困惑.

Using reflection, I'm attempting to find the set of types which inherit from a given base class. It didn't take long to figure out for simple types, but I'm stumped when it comes to generics.

对于这段代码,第一个 IsAssignableFrom 返回 true,但第二个返回 false.然而,最终的作业编译得很好.

For this piece of code, the first IsAssignableFrom returns true, but the second returns false. And yet, the final assignment compiles just fine.

class class1 { }
class class2 : class1 { }
class generic1<T> { }
class generic2<T> : generic1<T> { }

class Program
{
    static void Main(string[] args)
    {
        Type c1 = typeof(class1);
        Type c2 = typeof(class2);
        Console.WriteLine("c1.IsAssignableFrom(c2): {0}", c1.IsAssignableFrom(c2));

        Type g1 = typeof(generic1<>);
        Type g2 = typeof(generic2<>);
        Console.WriteLine("g1.IsAssignableFrom(g2): {0}", g1.IsAssignableFrom(g2));

        generic1<class1> cc = new generic2<class1>();
    }
}

那么如何在运行时确定一个泛型类型定义是否派生自另一个?

So how do I determine at run time whether one generic type definition is derived from another?

推荐答案

来自对另一个问题的回答:>

public static bool IsAssignableToGenericType(Type givenType, Type genericType)
{
    var interfaceTypes = givenType.GetInterfaces();

    foreach (var it in interfaceTypes)
    {
        if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType)
            return true;
    }

    if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
        return true;

    Type baseType = givenType.BaseType;
    if (baseType == null) return false;

    return IsAssignableToGenericType(baseType, genericType);
}

(如果您喜欢答案,请为链接的答案点赞,因为代码不是我的.)

(If you like the answer please upvote the linked answer since the code isn’t mine.)

这篇关于将 IsAssignableFrom 与“开放"泛型类型一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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