加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:07:20 所属栏目:百科 来源:网络整理
导读:我有一个C#方法说: MyMethod(int num,string name,Color color,MyComplexType complex) 使用反射,我如何清楚地识别任何方法的每个参数类型? 我想通过参数类型执行一些任务.如果类型是简单的int,string或boolean然后我做一些事情,如果它是Color,XMLDocument
我有一个C#方法说:
MyMethod(int num,string name,Color color,MyComplexType complex)

使用反射,我如何清楚地识别任何方法的每个参数类型?
我想通过参数类型执行一些任务.如果类型是简单的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提到的IsPrimitive和IsByRef.此外,您还可以使用IsValueType. System.Type类中有大量的Is *属性.你最好的选择是检查每个Is *属性的MSDN文档,即… IsClass声明……

Gets a value indicating whether the
Type is a class; that is,not a value
type or interface.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读