Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/201.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取泛型参数的类型?_C#_Generics - Fatal编程技术网

C# 如何获取泛型参数的类型?

C# 如何获取泛型参数的类型?,c#,generics,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) } void示例() { //这里我想得到T的类型(如果T是一个基元,我怎么能得到 //种类(int、bool、string)不是类) } 使用以下方法获取T的类型: Type

如何获取泛型参数的类型

例如:

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)
} 
void示例()
{
//这里我想得到T的类型(如果T是一个基元,我怎么能得到
//种类(int、bool、string)不是类)
} 

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

Type typeParameterType = typeof(T);

您还可以从类型T的实例中获取类型T:

instance.GetType();
这将得到类型T的类型对象

type.IsPrimitive
将告诉您它是否是基本类型之一,请参阅此处的列表:

另外,请注意,尽管
string
是一种基本类型,它与.NET系统非常集成,但它不是一种原语
System.String
是一个成熟的类,而不是原语

Type type = typeof(T);