使用泛型类型作为异步方法的返回类型 [英] Using a generic type as a return type of an async method
问题描述
一个previous问题让我想知道为什么下面的方法将提高一个编译时错误:
异步方法的返回类型必须为void,任务或任务
块引用>公共异步牛逼MyMethodAsync< T>()其中T:任务
{
//无关code这里返回任务
}由于我们在编译时知道T是总是
工作
或派生类型,为什么不这项工作?修改
我问的原因是,一个方法可以返回一个
工作
或任务< T>
。比方说,该方法可以返回,我不希望重复code。当然,这是所有的理论,不包换生产目的。
编辑2
找到由卢西恩Wischik一个伟大的文章:
的为什么一定要异步返回任务的解决方案三个问题:
仅仅因为
T
是工作
或派生类型并不意味着它是工作
或任务< T>
。你所期望的,如果我叫MyMethodAsync< MyCustomTask>
,其中MyCustomTask
从导出任务
?编译器需要知道是否是构建一个状态机返回
工作
或任务< T>
当它编译方法 - 它在不同情况下使用不同的辅助类如果异步方法具有
工作
的返回类型,任何收益
语句不能指定一个值;如果有的返回类型任务< T>
的收益
语句必须指定一个值,该值隐式转换为T
。如何能在MyMethodAsync
工作?这是一个有点像说:我的方法可以是无效
或返回T
- 当你调用它,你可以决定目前还不清楚你想要什么在这里实现,但基本上这是行不通的。
A previous question made me wonder why the following method would raise a compile time error:
The return type of an async method must be void, Task or Task
public async T MyMethodAsync<T>() where T : Task { // Irrelevant code here which returns a Task }
Since we know at compile time that T is always a
Task
or a derived type, why won't this work?Edit
The reason I'm asking is that a method may return a
Task
or aTask<T>
. Let's say the method can return either and I don't want to duplicate code.Of course this is all theoretical and isn't ment for production purposes.
Edit 2
Found a great article by Lucian Wischik: Why must async return Task
解决方案Three problems:
Just because
T
is "Task
or a derived type" doesn't mean that it'sTask
orTask<T>
. What would you expect if I calledMyMethodAsync<MyCustomTask>
whereMyCustomTask
derives fromTask
?The compiler needs to know whether it's building a state machine returning
Task
orTask<T>
when it compiles the method - it uses different helper classes in the different casesIf an async method has a return type of
Task
, anyreturn
statements can't specify a value; if it has a return type ofTask<T>
anyreturn
statements must specify a value which is implicitly convertible toT
. How can that work withinMyMethodAsync
? It's a bit like saying "my method is eithervoid
or returns aT
- you can decide when you call it".It's not clear what you're trying to achieve here, but basically this isn't going to work.
这篇关于使用泛型类型作为异步方法的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!