带有方法签名,如:
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://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;