确定派生自哪个泛型类型对象

时间:2011-05-19 06:33:13

标签: c# inheritance reflection

我有以下课程:

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;

1 个答案:

答案 0 :(得分:4)

如果您在编译时不知道类型,那么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<,>));

请注意,此不会用于查找已实现的接口,这有点棘手。