英文:
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<WordDocument> 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<WordDocument> GetFrontPage() => 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<WordDocument>
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 (=>
) as lambda expressions.
答案2
得分: 0
以下是已翻译的内容:
尝试使用:
Func<Task<WordDocument>> frontPage = async () => await GetFrontPage();
protected override async Task<WordDocument> GetFrontPage() => await Task.FromResult<WordDocument>(null);
英文:
try with:
Func<Task<WordDocument>> frontPage = async () => await GetFrontPage();
protected override async Task<WordDocument> GetFrontPage() => await Task.FromResult<WordDocument>(null);
答案3
得分: -1
这对我来说可以正常工作:
protected override async Task<WordDocument> GetFrontPage() => await Task.FromResult<WordDocument>(null);
英文:
This works for me:
protected override async Task<WordDocument> GetFrontPage() => await Task.FromResult<WordDocument>(null);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论