确定从泛型类型派生的类型
我有以下实用程序例程,用于确定类型是否派生自特定类型:
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);
}
}
}
I have the following utility routine which determine whether a type derives from a specific type:
private static bool DerivesFrom(Type rType, Type rDerivedType)
{
while ((rType != null) && ((rType != rDerivedType)))
rType = rType.BaseType;
return (rType == rDerivedType);
}
(actually I don't know whether there is a more convenient way to test the derivation...)
The problem is I want to determine whether a type derives from a generic type, but without specify the generic arguments.
For example I can write:
DerivesFrom(typeof(ClassA), typeof(MyGenericClass<ClassB>))
but what I need is the following
DerivesFrom(typeof(ClassA), typeof(MyGenericClass))
How can I achieve it?
Based on the example of Darin Miritrov, this is a sample application:
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将通用参数保持打开状态:
应该可以工作。示例:
另请注意 IsSubClassOf 方法的用法,该方法应该简化您的
DerivesFrom
方法并有点违背其目的。您还可以查看 IsAssignableFrom 方法。You could leave the generic parameter open:
should work. Example:
Also notice the usage of IsSubClassOf method which should simplify your
DerivesFrom
method and kind of defeat its purpose. There's also the IsAssignableFrom method you may take a look at.