如何使用反射获取 Task<T> 中类型 T 的属性?

How to get properties of type T in Task<T> using reflection?

我正在尝试使用反射获取 return 类型方法的属性。

我正在使用 MethodInfo.ReturnType 获取 return 类型的方法,因为我的方法是 async,所以我的类型是 Task<T>。在这种类型上使用 GetProperties 会得到属于 Task 的属性:ResultExceptionAsyncState。但是,我想获取底层类型 T 的属性。

带有签名的方法示例:

public async Task<MyReturnType> MyMethod()
var myMethodInfo = MyType.GetMethod("MyMethod");
var returnType = myMethodInfo.ReturnType; // Task<MyReturnType>
var myProperties = returnType.GetProperties(); // [Result, Exception, AsyncState]

如何获取Task中内部类型T的属性,而不是Task的属性?

您可以使用方法 GetGenericTypeDefinition() 确定类型是否为 Task 并使用 属性 GenericTypeArguments.

获取泛型类型参数

在这种情况下:

var myMethodInfo = MyType.GetMethod("MyMethod");
var returnType = myMethodInfo.ReturnType;

if (returnType.GetGenericTypeDefinition() == typeof(Task<>)) {
    var actualReturnType = returnType.GenericTypeArguments[0]; // MyReturnType
    var myProperties = actualReturnType.GetProperties(); // The properties of MyReturnType!
}