具有Nullable类型的MethodInfo.GetParameter()

时间:2013-08-27 02:01:23

标签: c# reflection nullable

我需要使用反射来调用方法。下面是我需要调用的方法:

public static void DoUpdate(int? operatorId, string name, string desc)
{
    // ...do some update work here...
}
我首先需要掌握这种方法的参数吧?所以我做了这段代码:

public static object[] GetMethodParms(MethodInfo method, NameValueCollection coll)
{
    var parms = method.GetParameters();
    // ...do some parse work here...
}
好吧,然后我觉得有些奇怪的事情发生了。如你所见,参数" operatorId"是Nullable,但parms [0]表明它只是一个简单的" System.Int32"。

为什么会发生这种情况,有人可以给我一个解释吗?

提前感谢。

修改#1

我抱歉道歉。我应该澄清一下:

我知道我可以通过以下代码检查某个类型是否为Nullable:

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) 
{ … }

或者,这是另一种方式:

var IsNullable = Nullable.GetUnderlyingType(p.ParameterType) !=null;

我不知道为什么MethodInfo.GetParameter()为Nullable(T)参数返回一个普通的底层类型。在我的情况下,&#34; int? operatorId&#34;返回&#34; System.Int32&#34;,我希望它是一个Nullable(int)。

1 个答案:

答案 0 :(得分:1)

您可以查看Nullable类型,如下所示

var parms = method.GetParameters();
foreach (ParameterInfo p in parms)
{
    var IsNullable = Nullable.GetUnderlyingType(p.ParameterType) !=null;
}
如果不是null类型,

Nullable.GetUnderlyingType将返回Nullable

通常我们可以检查可空类型如下

System.Type type = typeof(int?);
Console.WriteLine(type.FullName); // System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

但是当我们在运行时使用反射时,它会给下划线类型而不是nullbale类型。

int? i = 5;
Type t = i.GetType();
Console.WriteLine(t.FullName); //"System.Int32"   

MSDN中解释的原因如下

  

在Nullable类型上调用GetType会导致装箱操作   当类型被隐式转换为Object时执行。因此   GetType始终返回表示底层的Type对象   类型,而不是Nullable类型。

相关问题