是否可以测试仿制药的基础?

Is it possible to test for the base of a generic?

好吧,这听起来可能很奇怪,但我需要测试传递给我的 object 是否属于 ModelItem<T> 类型,而我并不关心 T 实际上是什么。换句话说,如果它是 ModelItem<int>ModelItem<string>ModelItem<Foo>,那么我需要 return true.

注意:如果我是 ModelItem<T> 的所有者,我会想只定义一个 IModelItem 类型的接口并将其分配为 ModelItem<T> 定义的一部分,但我无权访问源。

当然可以:

public bool IsIt(object thing)
{
    var type = thing.GetType();
    if (type.IsGenericType)
    {
        return type.GetGenericTypeDefinition() == typeof(MyThing<>);
    } 
    return false;
}

正在测试:

IsIt(new MyThing<int>()).Dump();
IsIt(new MyThing<string>()).Dump();
IsIt(new MyThing<Foo>()).Dump();
IsIt(5).Dump();

Returns

True
True
True
False