型が特定の型から派生しているかどうかを判断する次のユーティリティ ルーチンがあります。
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);
}
}
}