Await the result of Task using reflection in a non-generic method

后端 未结 2 1878
不知归路
不知归路 2021-01-12 01:03

Consider the following case:

class A
{
    public int Id;
}

class B : A
{

}

class Main
{
    public async Task Create(Type type)
    {
                 


        
相关标签:
2条回答
  • 2021-01-12 01:38

    As per my comment:

    Unlike interfaces, concrete types such as Task<TResult> cannot be covariant. See Why is Task not co-variant?. So Task<B> cannot be assigned to a Task<A>.

    The best solution I can think of is to use the underlying type Task to perform the await like so:

    var task = (Task)method.Invoke(this, new object[] { "humpf" });
    await task;
    

    Then you can use reflection to get the value of the Result:

    var resultProperty = typeof(Task<>).MakeGenericType(type).GetProperty("Result");
    A a = (A)resultProperty.GetValue(task);
    return a.Id;
    
    0 讨论(0)
  • 2021-01-12 01:52

    The above solution really helped me. I made a small tweak to the @Lukazoid solution...

    var resultProperty = typeof(Task<>).MakeGenericType(type).GetProperty("Result");
    A a = (A)resultProperty.GetValue(task);
    

    to

    dynamic a = task.GetType().GetProperty("Result")?.GetValue(task);
    
    0 讨论(0)
提交回复
热议问题