如何检查对象是否属于泛型类型?

Mat*_*ley 2 c#

为了争论,我有一个object.我无法修改我的函数的签名,因为我正在扩展其他人的类.

举一个具体的例子,我有以下内容:

class Foo<T> : SomeBaseClass
{
    public override MyFunction(object value)
    {
        // TODO: Figure out if value is an instance of Foo, though I don't care
        // what type was associated with it.
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法确保这value是某种Foo类型的实例?

Jon*_*eet 6

好吧,如果你想检查它是否是正好一个Foo<something>是相当容易:

Type type = value.GetType();
if (!type.IsGenericType)
{
    throw new ArgumentException("Not a generic type");
}
if (type.GetGenericTypeDefinition() != typeof(Foo<>))
{
    throw new ArgumentException("Not the right generic type");
}
Run Code Online (Sandbox Code Playgroud)

如果你需要决定它是从某种类型派生出来的Foo<T>还是稍微难一点 - 因为你不一定知道它在哪里是通用的.例如,它可能是:

class Bar : Foo<string>
Run Code Online (Sandbox Code Playgroud)

要么

class Baz<T> : Foo<T>
Run Code Online (Sandbox Code Playgroud)

使事情变得更容易的另一种方法可能是引入另一个非泛型类:

abstract class Foo : SomeBaseClass

class Foo<T> : Foo
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

if (value is Foo)
Run Code Online (Sandbox Code Playgroud)

当然,这也将允许其他类型派生Foo.在许多情况下,这确实不是问题,但这取决于您的具体情况.您也可以将任何不需要引用的成员T放入Foo,这样您就可以在不关心的情况下访问它们T.