internal /*async*/ void RunAsync()
{
var tasks = ...;
await Task.WhenAll(tasks);
}
在上面的示例中,IDE 通知我“''await 运算符只能在异步方法中使用”。它为我提供了修复方法,使我的方法签名async void
或async Task
internal /*async*/ void RunAsync()
{
var tasks = ...;
var t = Task.WhenAll(tasks);
await t;
}
在第二个示例中,它给出错误“找不到类型或命名空间等待”...await
未将颜色编码为语言关键字,并且 IDE 没有为我提供自动修复.
这是 VS 的错误吗?
最佳答案
在这两种情况下,代码都是无效的 C# 代码。因此,编译器/IDE 必须尽力找出您正在尝试执行的操作,并为您提供适当的错误消息。
In the above example, the IDE informs me "the ''await operator can only be used within an async method". It offers me fixes to make my method signature async void or async Task
VS 正在解析代码,并且非常确定此处的 await
旨在作为 await
运算符。该代码不是有效的 C#,但这就是您想要做的。因此,它为您提供了一个有用的建议,即您必须使用 async
关键字才能使 await
成为关键字。
In the second example, it gives the error "the type or namespace await cannot be found"... await is not color-coded as a language keyword and the IDE offers me no automatic fixes.
VS正在解析代码,不确定这里的await
是await
运算符还是类型。对于编译器来说,await t;
看起来很像int t;
。
Is this a VS bug?
这不是一个错误,因为代码一开始就是无效的 C#。但在第二种情况下,您可以要求提供更好的错误消息,并且 C# 编译器团队可能会也可能不会决定值得这样做,而不是开发其他功能。
对于上下文,请注意 await
is a contextual keyword 。如果存在 async
关键字,它只是一个关键字。 await
并不总是一个关键字,如果 VS 始终将其视为关键字,那将是一个错误。具体来说,在此处的两个代码示例中,await
不是关键字。 VS 在第一个示例中不遗余力地进行额外的后备解析,以检测开发人员打算使用 await
关键字的常见场景。
关于c# - 为什么VS2017说await是一个未知关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737522/