[英]Determine which genric type object is derived from
我有以下课程:
public abstract class CommandBase
{
... Stuff
}
public abstract class Command<TArgumentType>
: CommandBase where TArgumentType : class
{
protected TArgumentType Argument { get; private set; }
protected Command(TArgumentType argument)
{
Argument = argument;
}
}
public abstract class Command<TArgumentType, TReturnType>
: Command<TArgumentType> where TArgumentType : class
{
public TReturnType ReturnValue{ get; protected set; }
protected Command(TArgumentType argument) : base(argument)
{
}
}
如何确定对象的类型为Command<TArgumentType>
或Command<TArgumentType, TReturnType>
? 我不知道TArgumentType或TReturnType是什么特定类型。 还是我应该做一个简单的尝试/赶上:
var returnValue = object.ReturnValue;
如果您在编译时不知道类型,那么foo.ReturnValue
甚至都不会编译,除非它是dynamic
类型。
您可以使用如下形式:
static bool ContainsGenericClassInHierarchy(object value,
Type genericTypeDefinition)
{
Type t = value.GetType();
while (t != null)
{
if (t.IsGenericType
&& t.GetGenericTypeDefinition() == genericTypeDefinition)
{
return true;
}
t = t.BaseType;
}
return false;
}
这样称呼它:
// Single type parameter
bool x = ContainsGenericClassInHierarchy(foo, typeof(Command<>));
// Two type parameters
bool y = ContainsGenericClassInHierarchy(foo, typeof(Command<,>));
请注意,这不会为找到实现的接口,这是有点棘手的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.