相关疑难解决方法(0)

在任务<TResult>中将TResult转换为System.Object

我正在加载一个程序集并调用一个静态方法,该方法将使用MethodInfo.Invoke()通过反射创建一个类型为"MyClass1"的新对象(此类型在运行时指定).当方法是普通同步方法时,这可以正常工作.但是,被调用的方法是一个异步方法,它返回Task <MyClass1>,它将用于使用task.Result检索结果.

理想情况下,我应该在任务中使用MyClass1作为TResult,但类型仅在运行时确定,所以我不能这样做.我正在寻找一种方法来获得任务和结果.我试图将TResult转换为System.Object并将该类作为通用对象.以下是我为此目的使用的代码.

public static void LoadAssembly()
{
    // Calling static async method directly works fine
    Task<MyClass1> task1 = MyClass1.MakeMyClass1();
    MyClass1 myClass1 = task1.Result;

    // Calling static async method through reflection through exception.
    Assembly assembly = Assembly.LoadFrom(dllName);
    Type type = assembly.GetType("AsyncDll.MyClass1");
    var types = assembly.GetTypes(); 
    MethodInfo[] methodInfos = types[0].GetMethods(BindingFlags.Public | BindingFlags.Static);
    Type myClassType = types[0];
    MethodInfo mi = myClassType.GetMethod("MakeMyClass1");
    Object obj = Activator.CreateInstance(mi.ReflectedType);
    Task<Object> task = (Task<Object>)mi.Invoke(obj, null); // Exception occurs here.
    Object result = task.Result;
}
Run Code Online (Sandbox Code Playgroud)

以下是通过反射调用的方法(测试代码).这个

public class …
Run Code Online (Sandbox Code Playgroud)

c# asynchronous task

9
推荐指数
3
解决办法
8649
查看次数

标签 统计

asynchronous ×1

c# ×1

task ×1