为什么我不能在语句中将 Await 括在括号中? [英] Why can't I wrap Await in parenthesis in a statement?
问题描述
在 C# 中,我有一些代码如下:
In C#, I have some code that looks like:
(await GetBoolAsync()).ShouldBeTrue();
ShouldBeTrue()
是来自 Shouldly 库的扩展方法关于布尔值.
ShouldBeTrue()
is an extension method from the Shouldly library that operates on Booleans.
VB.NET 似乎不喜欢将 Await 关键字括在括号中:
VB.NET doesn't seem to like wrapping the Await keyword in parenthesis:
(Await GetBoolAsync()).ShouldBeTrue()
编译器在行首的左括号中报告语法错误.我可以通过声明一个中间变量来解决这个问题,但是有没有办法像 C# 这样在一行中实现这一点?
The compiler reports a syntax error on the opening parenthesis at the beginning of the line. I can work around it by declaring an intermediate variable, but is there a way to achieve this in one line like C#?
一个完整的控制台应用程序来重现这个:
A full console application to reproduce this:
Imports System.Runtime.CompilerServices
Module Module1
Sub Main
End Sub
Async Function Test() As Task
(Await GetBoolAsync()).ShouldBeTrue()
End Function
Function GetBoolAsync() As Task(Of Boolean)
Return Task.FromResult(True)
End Function
<Extension()>
Public Sub ShouldBeTrue(x As Boolean)
End Sub
End Module
该错误非常无用:
错误 BC30035:语法错误.
error BC30035: Syntax error.
推荐答案
这样做有一个特殊的语法 - 你应该使用 Call
关键字:
There is a special syntax for doing so - you should use the Call
keyword:
Async Function Test() As Task
Call (Await GetBoolAsync()).ShouldBeTrue()
End Function
那是因为您不能像在 C# 中那样在 Visual Basic 中直接调用非文字表达式的成员:
That's because you cannot directly call a member of non-literal expression in Visual Basic, like you would in C#:
(5).ToString() 'It is wrong!
在这种特殊情况下,这包括 Await
的结果.
And in this particular case this includes the result of Await
.
希望有帮助!
这篇关于为什么我不能在语句中将 Await 括在括号中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!