如何在C#方法中识别每种参数类型? [英] How to identify each parameter type in a C# method?

查看:72
本文介绍了如何在C#方法中识别每种参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#方法说:

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

使用反射,如何区分任何方法的每种参数类型? 我想按参数类型执行一些任务.如果类型是简单的int,字符串或布尔值,那么我会做一些事情,如果是Color,XMLDocument等,我会做其他事情,如果它是用户定义的类型,例如MyComplexType或MyCalci等,那么我想执行某些任务.

Using reflection, how can I distinctly identify each of the parameter types of any method? I want to perform some task by parameter type. If the type is simple int, string or boolean then I do something, if it is Color, XMLDocument, etc I do something else and if it is user defined type like MyComplexType or MyCalci etc then I want to do certain task.

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

I am able to retrieve all the parameters of a method using ParameterInfo and can loop through each parameter and get their types. But how can I identify each data type?

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

}

这是我创建一个propert网格排序页面的代码的一部分,在该页面中,我想显示带有所选方法的数据类型的参数列表.如果参数具有任何用户定义的类型/引用类型,那么我想进一步扩展它以显示其下具有数据类型的所有元素.

this is apart of my code to create a propert grid sort of page where I want to show the parameter list with data types for the selected method. If the parameter has any userdefined type/reference type then I want to expand it further to show all the elements under it with datatypes.

推荐答案

使用

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

If you need to check the System.Type once retrieved you can use IsPrimitive and IsByRef as mentioned by David. In addition you can also use IsValueType. There are a significant number of Is* properties within the System.Type class. Your best bet would be to check the MSDN documentation on each Is* property ie...IsClass states...

获取一个值,该值指示是否 类型是一个类;那不是一个值 类型或界面.

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类型执行此操作.两种方法都可以.

Therefore one could deduce that IsValueType does not need to be called. Keep in mind that a given type can return true across multiple properties in that IsClass could return true AND IsPassByRef could return true. Perhaps provide logic for the known CLR types since those will not change and you know those ahead of time and then build in the logic for complex types as defined by the user. You could take the approach of building in the logic to do this for the CLR types as well; either way would work.

这篇关于如何在C#方法中识别每种参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆