相关疑难解决方法(0)

在非泛型方法中使用反射等待Task <TDerived>的结果

考虑以下情况:

class A
{
    public int Id;
}

class B : A
{

}

class Main
{
    public async Task<int> Create(Type type)
    {
        MethodInfo method = this.GetType().GetMethod("Create", new Type[] { typeof(string) }).MakeGenericMethod(new Type[] { type });
        A a = await (Task<A>)method.Invoke(this, new object[] { "humpf" });
        return a.Id;
    }

    public async Task<T> Create<T>(string name) where T : A
    {
        T t = await Foo.Bar<T>(name);
        return t;
    }
}
Run Code Online (Sandbox Code Playgroud)

呼叫new Main().Create(typeof(B))将失败

无法将' System.Threading.Tasks.Task[B]'类型的对象强制转换为' System.Threading.Tasks.Task[A]'

我不太明白,因为在这种情况下,Generic Create<T>方法只返回始终从' …

c# generics reflection async-await

9
推荐指数
1
解决办法
2347
查看次数

标签 统计

async-await ×1

c# ×1

generics ×1

reflection ×1