为什么可以返回 Task<TResult> 当期望的是 Task?

huangapple go评论73阅读模式
英文:

Why can you return Task<TResult> when Task is expected?

问题

我弄了些任务,做了一个私有的静态异步方法,在延迟后返回一个随机数。我还创建了一个公共的静态方法,调用了私有的静态异步方法,但我忘记把返回类型从 Task 改成 Task&lt;int&gt;

public static Task&lt;int&gt; GetRandomNumber()
{
  return GetRandomNumberAsync();
}

private static async Task&lt;int&gt; 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&lt;int&gt;.

public static Task GetRandomNumber()
{
  return GetRandomNumberAsync();
}

private static async Task&lt;int&gt; 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&lt;T&gt;s are Tasks, 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.

huangapple
  • 本文由 发表于 2023年1月9日 15:28:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054229.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定