从泛型类型确定类型派生

Luc*_*uca 3 c# generics reflection derived-class

我有以下实用程序例程,它确定类型是否派生自特定类型:

private static bool DerivesFrom(Type rType, Type rDerivedType)
{
    while ((rType != null) && ((rType != rDerivedType)))
        rType = rType.BaseType;
    return (rType == rDerivedType);
}
Run Code Online (Sandbox Code Playgroud)

(实际上我不知道是否有更方便的方法来测试推导......)

问题是我想确定一个类型派生自泛型类型,但是没有指定泛型参数.

例如我可以写:

DerivesFrom(typeof(ClassA), typeof(MyGenericClass<ClassB>))
Run Code Online (Sandbox Code Playgroud)

但我需要的是以下内容

DerivesFrom(typeof(ClassA), typeof(MyGenericClass))
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现它?


基于Darin Miritrov的示例,这是一个示例应用程序:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace ConsoleApplication1
{
    public class MyGenericClass<T> { }
    public class ClassB {}
    public class ClassA : MyGenericClass<ClassB> { }

    class Program
    {
        static void Main()
        {
            bool result = DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));
            Console.WriteLine(result); // prints **false**
        }

        private static bool DerivesFrom(Type rType, Type rDerivedType)
        {
            return rType.IsSubclassOf(rDerivedType);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

您可以将通用参数保持为打开状态:

DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));
Run Code Online (Sandbox Code Playgroud)

应该管用.例:

public class ClassA { }
public class MyGenericClass<T>: ClassA { }

class Program
{
    static void Main()
    {
        var result = DerivesFrom(typeof(MyGenericClass<>), typeof(ClassA));
        Console.WriteLine(result); // prints True
    }

    private static bool DerivesFrom(Type rType, Type rDerivedType)
    {
        return rType.IsSubclassOf(rDerivedType);
    }
}
Run Code Online (Sandbox Code Playgroud)

还要注意IsSubClassOf方法的用法,方法应该简化你的DerivesFrom方法和失败的目的.另外还有IsAssignableFrom你可以看一看方法.