使用泛型类型作为异步方法的返回类型 [英] Using a generic type as a return type of an async method

查看:427
本文介绍了使用泛型类型作为异步方法的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个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 a Task<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's Task or Task<T>. What would you expect if I called MyMethodAsync<MyCustomTask> where MyCustomTask derives from Task?

  • The compiler needs to know whether it's building a state machine returning Task or Task<T> when it compiles the method - it uses different helper classes in the different cases

  • If an async method has a return type of Task, any return statements can't specify a value; if it has a return type of Task<T> any return statements must specify a value which is implicitly convertible to T. How can that work within MyMethodAsync? It's a bit like saying "my method is either void or returns a T - 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆