【问题标题】:Determine type derivation from generic type从泛型类型确定类型派生
【发布时间】:2011-05-24 04:37:50
【问题描述】:

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

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

(其实不知道有没有更方便的推导测试方法……)

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

例如我可以写:

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

【问题讨论】:

    标签: c# generics reflection derived-class


    【解决方案1】:

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

    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,你看过我提供的样本吗?它出什么问题了?您有一个基类和一个派生的泛型类,与您在问题中描述的完全一样。至少在这个例子中使用开放的泛型类型是有效的。如果它不适合你,你需要提供一个完整的例子和你的类层次结构,这样我们就可以看到它有什么问题。
    • 是的,事实上,我查看了我的 cmets:该示例正在运行。我需要更深入地了解我的应用程序。
    • 找到我的应用程序不工作的原因。参见示例:ClassA 派生自泛型类型,反之亦然。
    猜你喜欢
    • 1970-01-01
    • 2014-03-22
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2023-02-03
    • 2012-09-08
    • 2015-01-26
    相关资源
    最近更新 更多