英文:
Why can you return Task<TResult> when Task is expected?
问题
我弄了些任务,做了一个私有的静态异步方法,在延迟后返回一个随机数。我还创建了一个公共的静态方法,调用了私有的静态异步方法,但我忘记把返回类型从 Task
改成 Task<int>
。
public static Task<int> GetRandomNumber()
{
return GetRandomNumberAsync();
}
private static async Task<int> GetRandomNumberAsync()
{
await Task.Delay(2000);
var rnd = new Random();
return rnd.Next();
}
这只是一种简写吗?如果不是,这是否意味着如果期望基类,你总是可以返回一个派生类?
英文:
As I was messing with tasks, I made a private static async method that returns a random number after a delay. I had also made a public static method that calls the private static async method, but I had forgotten to change the return type from Task
to Task<int>
.
public static Task GetRandomNumber()
{
return GetRandomNumberAsync();
}
private static async Task<int> GetRandomNumberAsync()
{
await Task.Delay(2000);
var rnd = new Random();
return rnd.Next();
}
Is this just some shorthand version at work? If not, does that mean you can always return a derived class if the base class is expected?
答案1
得分: 0
是的。所有的Task<T>
都是Task
,因此将引用从前者转换为后者总是可以的。这对于返回值、参数以及其他情况都是成立的。
这只是普通的继承,如果这对您来说不熟悉,我建议阅读介绍,因为这是一个相当基础的主题。
英文:
> does that mean you can always return a derived class if the base class is expected?
Yes. All Task<T>
s are Task
s, so it is always fine to convert references from the former to the later. This is true both for return values as well as parameters and other in other circumstances.
This is just normal inheritance, if this is unfamiliar to you I would suggest reading the introduction, since this is a fairly fundamental topic.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论