I am trying to get the properties of a return type of a method using reflection.
I am getting the return type of the method using MethodInfo.ReturnType
, which yields my a type of Task<T>
since my method is async
. Using GetProperties
on this type yields me with the properties belonging to Task
: Result
, Exception
, AsyncState
. However, I want to get the properties of the underlying type T.
Example for method with signature:
public async Task<MyReturnType> MyMethod()
var myMethodInfo = MyType.GetMethod("MyMethod");
var returnType = myMethodInfo.ReturnType; // Task<MyReturnType>
var myProperties = returnType.GetProperties(); // [Result, Exception, AsyncState]
How can I get the properties of the inner type T in Task in stead of the properties of Task?
You can determine if the type is a Task
with the method GetGenericTypeDefinition()
and get the generic type arguments with the property GenericTypeArguments
.
In this case:
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!
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.