如何在C#方法中识别每种参数类型? [英] How to identify each parameter type in a C# method?
问题描述
我有一个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.
推荐答案
使用
如果检索后需要检查 If you need to check the 获取一个值,该值指示是否
类型是一个类;那不是一个值
类型或界面. Gets a value indicating whether the
Type is a class; that is, not a value
type or interface. 因此,可以推断出 Therefore one could deduce that 这篇关于如何在C#方法中识别每种参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!System.Type
,则可以使用David提到的IsPrimitive
和IsByRef
.另外,您还可以使用IsValueType
. System.Type 类中有大量Is *属性. .最好的选择是检查每个Is *属性的MSDN文档,即... IsClass
状态... 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...
IsValueType
不需要被调用.请记住,给定类型可以跨多个属性返回true,因为IsClass
可以返回true,而IsPassByRef
可以返回true.也许为已知的CLR类型提供逻辑,因为这些不会改变,并且您会提前知道它们,然后为用户定义的复杂类型构建逻辑.您也可以采用构建逻辑的方法来对CLR类型执行此操作.两种方法都可以.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.