如何获取泛型参数的类型?
例如:
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)
}
Type type = typeof(T);
type.IsPrimitive
将告诉您它是否是原始类型之一,详见此处列表:http://msdn.microsoft.com/en-us/library/system.type.isprimitive.aspx
另外,请注意,尽管string
是一个基本类型,与.NET系统非常集成,但它不是一个原始类型。System.String
是一个完整的类,而不是一个原始类型。您可以通过 T 类型的实例获取 T 的类型:
instance.GetType();