У меня есть следующая служебная программа, которая определяет, является ли тип производным от определенного типа:
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))
Как мне этого добиться?
На примере Дарин Миритров , это пример приложения:
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);
}
}
}