如何检查方法参数是否为Nullable<>;如果';s也是一个“;out”;参数
本文关键字:参数 out 一个 lt 方法 检查 何检查 是否 gt Nullable 如果 | 更新日期: 2023-09-27 18:30:13
使用方法签名,如:
public interface TestInterface
{
void SampleMethodOut(out int? nullableInt);
void SampleMethod(int? nullableInt);
}
我使用typeof(TestInterface).GetMethods()[1].GetParameters()[0].ParameterType来获取类型,然后检查IsGenericType和Nullable.GetUnderlyingType。如何使用带有out参数的方法来完成此操作?

Doh,忽略我之前的回答。
您使用Type.IsByRef,如果是,则调用Type.GetElementType():
var type = method.GetParameters()[0].ParameterType;
if (type.IsByRef)
{
// Remove the ref/out-ness
type = type.GetElementType();
}
对于所有刚刚找到此页面的
c#文档页面展示了一种简洁的方法
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#how-识别无价值型
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;