【问题标题】:MethodInfo.GetParameter() with Nullable type具有 Nullable 类型的 MethodInfo.GetParameter()
【发布时间】:2013-08-27 10:40:15
【问题描述】:

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

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) 参数返回一个普通的基础类型。就我而言,“int?operatorId”返回“System.Int32”,我希望它是 Nullable(int)。

【问题讨论】:

    标签: c# reflection nullable


    【解决方案1】:

    你可以检查 Nullable 类型如下

    var parms = method.GetParameters();
    foreach (ParameterInfo p in parms)
    {
        var IsNullable = Nullable.GetUnderlyingType(p.ParameterType) !=null;
    }
    

    Nullable.GetUnderlyingType 将在不是Nullable 类型的情况下返回null

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

    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 类型。

    【讨论】:

    • 是的,谢谢达米特。你从这个链接得到了这些:msdn.microsoft.com/zh-cn/library/ms366789(v=vs.100).aspx,对吧? :) 但是你知道,MethodInfo.GetParameters() 是微软提供的,我们不能改变内部代码。我想知道为什么 ms 选择了这种行为,他们不能只为我返回一个可为空的类型吗?
    • 再次感谢达米特。这是检查 Nullable 类型的好方法。很高兴听到这个消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    相关资源
    最近更新 更多