如何在C#方法中识别每个参数类型?

我有一个C#方法说:

MyMethod(int num, string name, Color color, MyComplexType complex) 

使用reflection,我如何清楚地识别任何方法的每个参数类型? 我想通过参数类型执行一些任务。 如果类型是简单的int,string或boolean然后我做一些事情,如果它是Color,XMLDocument等我做其他事情,如果它是用户定义的类型,如MyComplexType或MyCalci等,那么我想做某些任务。

我能够使用ParameterInfo检索方法的所有参数,并可以遍历每个参数并获取它们的类型。 但是如何识别每种数据类型?

 foreach (var parameter in parameters) { //identify primitive types?? //identify value types //identify reference types } 

编辑:这是我的代码的一部分,以创建一个属性网格排序页面,我想显示所选方法的数据类型的参数列表。 如果参数有任何用户定义的类型/引用类型,那么我想进一步展开它以显示数据类型下的所有元素。

使用ParameterInfo.ParameterType

  using System; using System.Reflection; class parminfo { public static void mymethod ( int int1m, out string str2m, ref string str3m) { str2m = "in mymethod"; } public static int Main(string[] args) { Console.WriteLine("\nReflection.Parameterinfo"); //Get the ParameterInfo parameter of a function. //Get the type. Type Mytype = Type.GetType("parminfo"); //Get and display the method. MethodBase Mymethodbase = Mytype.GetMethod("mymethod"); Console.Write("\nMymethodbase = " + Mymethodbase); //Get the ParameterInfo array. ParameterInfo[]Myarray = Mymethodbase.GetParameters(); //Get and display the ParameterInfo of each parameter. foreach (ParameterInfo Myparam in Myarray) { Console.Write ("\nFor parameter # " + Myparam.Position + ", the ParameterType is - " + Myparam.ParameterType); } return 0; } } 

如果需要在检索后检查System.Type ,可以使用David提到的IsPrimitiveIsByRef 。 此外,您还可以使用IsValueType 。 System.Type类中有大量的Is *属性。 你最好的选择是检查每个Is *属性的MSDN文档,即…… IsClass声明……

获取一个值,该值指示Type是否为类; 也就是说,不是值类型或接口。

因此可以推断出不需要调用IsValueType 。 请记住,给定类型可以在多个属性中返回true,因为IsClass可以返回true并且IsPassByRef可以返回true。 也许为已知的CLR类型提供逻辑,因为它们不会改变,您可以提前知道它们,然后构建用户定义的复杂类型的逻辑。 您可以采用构建逻辑的方法来为CLR类型执行此操作; 无论哪种方式都可行。

要获取参数的实际Type ,请使用ParameterInfo值上的ParameterInfo 。 使用该值,有几种方法可以使用它来识别类型。 最简单的方法是直接与已知类型进行比较

 if (parameter.ParameterType == typeof(int)) { ... } 

或者在类型不可用的情况下,可以使用名称匹配(尽管由于重构操作可能会错过字符串常量并默默地中断应用程序,因此这有点不太常见)

 if (parameter.ParameterType.Name == "TheTypeName") { ... }