在 .NET 泛型方法中,如何获取实际参数类型

In a .NET generic method, how to get the actual parameters type

在泛型方法中,我想知道传递的实际参数的类型。例如我有两个 classes:

class A {}
class B {}

然后一个方法以任何 class 作为参数:

void M<T>(T instance)
{
    // how to tell what is the type of T if instance is null?
    // (so instance.GetType() won't work)
}

例如如何在调用的方法中区分以下两个调用:

M<A>(null);
M<B>(null);

这可能吗?方法 MethodBase.GetCurrentMethod() returns 泛型方法定义,而不是实际的泛型参数。 StackTrace 帧也是如此。

typeof(T) 为您提供类型。通常当我在通用 class 或方法中时,这是我想要基于的类型。

instance.GetType() 获取实例的类型,但我可能正在寻找已实现的接口或基础 class,而 .GetType() 永远不会 return。另外,正如您所指出的,如果您在 null 上调用 .GetType(),您将得到一个 null 引用异常。