【问题标题】:Can't use literal curly braces around interpolated string不能在插值字符串周围使用文字花括号
【发布时间】:2018-02-22 22:37:43
【问题描述】:

我一直在阅读 this SO post carefully,试图将花括号文字放在我的插值字符串周围。

string testString = "foo";
string testResult1 = $"{testString}"; // result = "foo" as expected
string testResult2 = $"{{testString}}"; // result = "{testString}" - UH OH

我对@9​​87654323@ 的预期结果是“{foo}”。我试过用反斜杠转义外部卷曲,但这不起作用,我没想到会这样。如何在插值字符串变量周围放置文字花括号?一个更准确的例子是:

string testResult3 = $"I want to eat some {{testString}} please.";

预期:“我想吃点{foo}。”

实际:“我想吃点 {testString}。”

我怎样才能做到这一点? (我也在$" 之间尝试了@,但没有任何乐趣。)

【问题讨论】:

  • 两个花括号计算为一个文字花括号。因此,您需要三个花括号:string testResult2 = $"{{{testString}}}"; 来生成 {foo}
  • @ChrisR.Timmons 更适合回答 :)
  • 我们有一个赢家...克里斯,请这样发布您的答案。

标签: c# c#-6.0


【解决方案1】:

来自Chris R. Timmons

两个花括号计算为一个字面花括号。因此你需要三个花括号:

string testResult2 = $"{{{testString}}}";

...生成{foo}

【讨论】:

    猜你喜欢
    • 2018-11-17
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 2023-01-29
    相关资源
    最近更新 更多