Casting TResult in Task to System.Object

后端 未结 3 1911
误落风尘
误落风尘 2020-12-16 01:54

I am loading an assembly and calling a static method that will create a new object of type “MyClass1” (this type is specified at runtime) through reflection using MethodInfo

3条回答
  •  庸人自扰
    2020-12-16 02:15

    You cannot cast Task to Task, because Task is not covariant (it's not contravariant, either). The simplest solution would be to use some more reflection:

    var task   = (Task) mi.Invoke (obj, null) ;
    var result = task.GetType ().GetProperty ("Result").GetValue (task) ;
    

    This is slow and inefficient, but usable if this code is not executed often. As an aside, what is the use of having an asynchronous MakeMyClass1 method if you are going to block waiting for its result?

    提交回复
    热议问题