当不用于插值时,“$”字符串前缀是什么意思?

What does a '$' string prefix mean when not used for interpolation?

我刚刚在 .NET Core configuration 上的一篇文章中看到这段代码,字典键对我来说很陌生:

static IReadOnlyDictionary<string, string> DefaultConfigurationStrings{get;} = new Dictionary<string, string>()
    {
        ["Profile:UserName"] = Environment.UserName,
        [$"AppConfiguration:ConnectionString"] = DefaultConnectionString,
        [$"AppConfiguration:MainWindow:Height"] = "400",
        [$"AppConfiguration:MainWindow:Width"] = "600",
        [$"AppConfiguration:MainWindow:Top"] = "0",
        [$"AppConfiguration:MainWindow:Left"] = "0",
    };

为什么是 $,为什么是 [...]?与不使用逗号分隔的键值对有关吗?

括号里的是以前的新index initializers. It's just another way to initialize a dictionary that's a bit more readable than the collection initializers

至于字符串,在不使用插值的时候,就是一个简单的字符串,仅此而已。据推测,编译器甚至不会为此类字符串生成 string.Format 调用。您也可以删除 $(当不使用任何不同的功能时,它与逐字字符串文字相同)。

$"" 字符串 可能 的一个可能原因是,它是对源代码预处理器或静态分析工具的提示,该字符串不知何故特别的。我已经看到类似的东西与逐字字符串文字一起使用,以防止 ReSharper 建议将字符串翻译为 i18n。不过,这是您需要在构建环境中寻找的东西。