如何获取Generic参数的类型?

Dav*_*rák 4 c# generics

我怎样才能获得泛型参数的类型?

例如:

void Example<T>()
{
  // Here I want to get the type of T (and how can I get if T is a primitive 
  // kind (int,bool,string) not class)
} 
Run Code Online (Sandbox Code Playgroud)

Dav*_*Yaw 8

Type type = typeof(T);
Run Code Online (Sandbox Code Playgroud)

这将获得类型T的类型对象.

type.IsPrimitive会告诉你它是否是原始类型之一,请参见此处的列表:http://msdn.microsoft.com/en-us/library/system.type.isprimitive.aspx

另请注意,虽然它string是一种与.NET系统非常集成的基本类型,但它不是原始类型.System.String是一个完整的阶级,而不是原始阶级.


CD.*_*D.. 6

使用以下方法获取T的类型:

Type typeParameterType = typeof(T);
Run Code Online (Sandbox Code Playgroud)

typeof(C#参考)