如果方法参数也是“ out”参数,如何通过反射检查方法参数是否为Nullable <>?

问题描述 投票:2回答:2

带有方法签名,如:

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

我正在使用typeof(TestInterface).GetMethods()[1].GetParameters()[0].ParameterType获取类型,然后检查IsGenericTypeNullable.GetUnderlyingType。如何使用带有out参数的方法执行此操作?

c# reflection parameters nullable out
2个回答
3
投票

Doh,请忽略我之前的回答。

您使用Type.IsByRef,如果是,请呼叫Type.GetElementType()

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

0
投票

[对于刚刚找到此页面的每个人

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;
© www.soinside.com 2019 - 2024. All rights reserved.