How to call a generic async method using reflection

后端 未结 4 993
死守一世寂寞
死守一世寂寞 2020-12-13 13:42
public interface IBar {
}
public class Bar : IBar {
}
public class Bar2 : IBar {
}
public interface IFoo {
  Task Get(T o) where T : IBar;
}
public         


        
4条回答
  •  猫巷女王i
    2020-12-13 14:38

    Based on your example you know type of returned object at compile time -> IFoo, so you can use normal casting (IFoo)

    var method = typeof(IFoo).GetMethod(nameof(IFoo.Get));
    var generic = method.MakeGenericMethod(typeof(IBar));
    var task = (Task)generic.Invoke(foo, new [] { bar2 });
    
    IBar result = await task;
    

    If you don't know a type at compile time, then simply use dynamic keyword

    var method = typeof(IFoo).GetMethod(nameof(IFoo.Get));
    var generic = method.MakeGenericMethod(bar2.GetType());
    dynamic task = generic.Invoke(foo, new [] { bar2 });
    
    IBar result = await task;
    

    But if type of the task not a Task at runtime - exception will be thrown
    And if you need concrete type of IBar then

    var concreteResult = Convert.ChangeType(result, bar2.GetType()); 
    

提交回复
热议问题