Sri*_*ddy 6 c# reflection methods types
我有一个C#方法说:
MyMethod(int num, string name, Color color, MyComplexType complex)
Run Code Online (Sandbox Code Playgroud)
使用反射,我如何清楚地识别任何方法的每个参数类型?我想通过参数类型执行一些任务.如果类型是简单的int,string或boolean然后我做一些事情,如果它是Color,XMLDocument等我做其他事情,如果它是用户定义的类型,如MyComplexType或MyCalci等,那么我想做某些任务.
我能够使用ParameterInfo检索方法的所有参数,并且可以遍历每个参数并获取它们的类型.但是如何识别每种数据类型?
foreach (var parameter in parameters)
{
//identify primitive types??
//identify value types
//identify reference types
}
Run Code Online (Sandbox Code Playgroud)
编辑:这是我的代码的一部分,以创建一个属性网格排序页面,我想显示所选方法的数据类型的参数列表.如果参数具有任何用户定义的类型/引用类型,那么我想进一步扩展它以显示其下的所有元素以及数据类型.
Aar*_*ver 12
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你需要检查System.Type一次检索,你可以使用IsPrimitive和IsByRef大卫提到的.另外你也可以使用IsValueType.System.Type类中有大量的Is*属性.你最好的选择是检查每个Is*属性的MSDN文档,即...... IsClass状态......
获取一个值,该值指示Type是否为类; 也就是说,不是值类型或接口.
因此可以推断出IsValueType不需要调用.请记住,给定类型可以在多个属性中IsClass返回true,因为它可以返回true并且IsPassByRef可以返回true.也许为已知的CLR类型提供逻辑,因为它们不会改变,您可以提前知道它们,然后构建用户定义的复杂类型的逻辑.您可以采用构建逻辑的方法来为CLR类型执行此操作; 无论哪种方式都可行.