简体   繁体   English

C# 等待,空合并,字符串插值不编译

[英]C# Await, null-coalescing, string interpolation does not compile

When conditionally awaiting a task using the null coalescing operator inside a string interpolation, I got an unexpected compilation error that my async method lacks an await, and that await isn't possible outside of an async context:在字符串插值中使用 null 合并运算符有条件地等待任务时,出现意外的编译错误,即我的异步方法缺少等待,并且在异步上下文之外无法等待:

using System;
using System.Threading.Tasks;
                    
public class Program
{
    public static async Task Main()
    {
        Task<string> isNull = null;
        var result = "World";
        var helloWorld = $"Hello {await (isNull ?? Task.FromResult(result))}";
        Console.WriteLine(helloWorld);
    }
}
Compilation error (line 10, col 29): The name 'await' does not exist in the current context
Compilation error (line 6, col 27): This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

I assume this is due to some compilator details that I am not aware of, and can't be avoided, but I would like to understand it.我认为这是由于一些我不知道并且无法避免的编译器细节,但我想了解它。

Link to fiddle describing issue链接到描述问题的小提琴

It looks like you encountered a roslyn bug: https://github.com/do.net/roslyn/issues/39149看起来您遇到了 roslyn 错误: https://github.com/do.net/roslyn/issues/39149

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM