表达体函数的奇怪行为

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

Expression bodied Function Weird Behavior

问题

这段代码的中文翻译如下:

当我使用以下代码:

var frontPage = await GetFrontPage();

protected override async Task<WordDocument> GetFrontPage()
{
    return null;
}

这段代码运行良好,我在frontPage变量中得到了null值。但当我将函数重写为:

protected override Task<WordDocument> GetFrontPage() => null;

我得到了一个NullReferenceException异常。

有人能帮助我理解这两个语句之间的区别吗?

英文:

When I am using

    var frontPage = await GetFrontPage();

    protected override async Task&lt;WordDocument&gt; GetFrontPage()
    {
        return null;
    }

This code works fine and I am getting null value in frontpage variable. but when I am rewriting the function as

protected override Task&lt;WordDocument&gt; GetFrontPage() =&gt; null;

I am getting an NullReferenceException.

Could anyone help me to understand the difference between the two statements.?

答案1

得分: 5

你的第一个声明是async,因此编译器生成适当的代码,使其返回一个Task<WordDocument>,该任务的结果是方法的结果。任务本身不是空的 - 它的 result 是空的。

你的第二个声明 async,因此它只返回一个空引用。任何等待或以其他方式取消引用该空引用的代码确实会导致抛出 NullReferenceException

只需在第二个声明中添加 async 修饰符,它将与第一个声明一样工作。

请注意,这里没有 lambda 表达式 - 你的第二个声明是一个 表达体方法。它只使用与 lambda 表达式相同的语法 (=>)。

英文:

> Could anyone help me to understand the difference between the two statements.?

Your first declaration is async, so the compiler generates appropriate code to make it return a Task&lt;WordDocument&gt; which has a result with the result of the method. The task itself is not null - its result is null.

Your second declaration is not async, therefore it just returns a null reference. Any code awaiting or otherwise-dereferencing that null reference will indeed cause a NullReferenceException to be thrown.

Just add the async modifier to the second declaration and it'll work the same as the first.

Note that there are no lambda expressions here - your second declaration is an expression-bodied method. It just uses the same syntax (=&gt;) as lambda expressions.

答案2

得分: 0

以下是已翻译的内容:

尝试使用:

    Func&lt;Task&lt;WordDocument&gt;&gt; frontPage = async () =&gt; await GetFrontPage();

    protected override async Task&lt;WordDocument&gt; GetFrontPage() =&gt; await Task.FromResult&lt;WordDocument&gt;(null);
英文:

try with:

Func&lt;Task&lt;WordDocument&gt;&gt; frontPage = async () =&gt; await GetFrontPage();

protected override async Task&lt;WordDocument&gt; GetFrontPage() =&gt; await Task.FromResult&lt;WordDocument&gt;(null);

答案3

得分: -1

这对我来说可以正常工作:

    protected override async Task<WordDocument> GetFrontPage() => await Task.FromResult<WordDocument>(null);
英文:

This works for me:

    protected override async Task&lt;WordDocument&gt; GetFrontPage() =&gt; await Task.FromResult&lt;WordDocument&gt;(null);

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

发表评论

匿名网友

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

确定