从泛型类型确定类型派生

3
我有以下实用程序例程,用于确定一个类型是否派生自特定类型:
private static bool DerivesFrom(Type rType, Type rDerivedType)
{
    while ((rType != null) && ((rType != rDerivedType)))
        rType = rType.BaseType;
    return (rType == rDerivedType);
}
< p >< em >(实际上我不知道是否有更方便的方法来测试导出...) < p >问题在于我想确定一个类型是否从泛型类型派生,但是不指定泛型参数。 < p >例如,我可以编写:
DerivesFrom(typeof(ClassA), typeof(MyGenericClass<ClassB>))

但我需要的是以下内容。
DerivesFrom(typeof(ClassA), typeof(MyGenericClass))

我该如何实现它?


根据 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);
        }
    }
}
1个回答

5
您可以将泛型参数保持开放状态:
DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));

应该可以正常工作。例如:
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);
    }
}

还要注意使用IsSubClassOf方法,它应该简化您的DerivesFrom方法并有点击败它的目的。还有IsAssignableFrom方法,您也可以查看一下。


@Luca,你看过我提供的示例了吗?有什么问题吗?你有一个基类和一个派生泛型类,正如你在问题中描述的那样。在这个示例中,使用开放式泛型类型至少是有效的。如果对你不起作用,你需要提供一个完整的示例,包括你的类层次结构,以便我们可以看到其中的问题所在。 - Darin Dimitrov
是的,事实上我已经审查了我的评论:这个例子是可以工作的。我需要更深入地研究我的应用程序。 - Luca
找到了我的应用程序为什么无法工作的原因。看这个例子:ClassA继承自泛型类型,而不是反过来。 - Luca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接