3

型が特定の型から派生しているかどうかを判断する次のユーティリティ ルーチンがあります。

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

1 に答える 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メソッドもあります。

于 2010-12-12T09:57:17.080 に答える