【问题标题】:How to check whether a method parameter is Nullable<> using reflection if it's also an "out" parameter?如果方法参数也是“out”参数,如何使用反射检查方法参数是否为 Nullable<>?
【发布时间】:2012-04-19 09:40:34
【问题描述】:

使用方法签名,例如:

public interface TestInterface
{
    void SampleMethodOut(out int? nullableInt);
    void SampleMethod(int? nullableInt);
}

我使用typeof(TestInterface).GetMethods()[1].GetParameters()[0].ParameterType 获取类型,然后检查IsGenericTypeNullable.GetUnderlyingType。如何使用带有 out 参数的方法做到这一点?

【问题讨论】:

  • 对于不是out参数的IsGenericType是true并且Nullable.GetUnderlyingType返回Int32,但是对于out参数它是false和null。
  • 那么对于非输出参数,ParameterType 返回typeof(Nullable&lt;int&gt;) -- 它对于输出参数返回什么?

标签: c# reflection parameters nullable out


【解决方案1】:

适合所有刚刚找到此页面的人

c# 文档页面显示了一种简洁的方法
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#how-to-identify-a-nullable-value-type

Console.WriteLine($"int? is {(IsNullable(typeof(int?)) ? "nullable" : "non nullable")} type");
Console.WriteLine($"int is {(IsNullable(typeof(int)) ? "nullable" : "non-nullable")} type");

bool IsNullable(Type type) => Nullable.GetUnderlyingType(type) != null;

// Output:
// int? is nullable type
// int is non-nullable type

使用反射,这是您获取参数类型的方式:

typeof(MyClass).GetMethod("MyMethod").GetParameters()[0].ParameterType;

【讨论】:

    【解决方案2】:

    Doh,忽略我之前的回答。

    您使用Type.IsByRef,如果是,则调用Type.GetElementType()

    var type = method.GetParameters()[0].ParameterType;
    if (type.IsByRef)
    {
        // Remove the ref/out-ness
        type = type.GetElementType();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多