【问题标题】:Escape curly brace '{' in String.Format [duplicate]String.Format 中的转义大括号“{”[重复]
【发布时间】:2011-04-15 23:44:39
【问题描述】:

使用 String.Format 方法时如何显示文字大括号字符?

例子:

sb.AppendLine(String.Format("public {0} {1} { get; private set; }", 
prop.Type, prop.Name));

我希望输出如下所示:

public Int32 MyProperty { get; private set; }

【问题讨论】:

    标签: c# .net string


    【解决方案1】:

    使用双括号 {{}},这样你的代码就变成了:

    sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
    prop.Type, prop.Name));
    
    // For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
    // public Foo Bar { get; private set; }
    

    【讨论】:

    • 直接来自文档:要在格式中指定单个文字大括号字符,请指定两个前导或尾随大括号字符;即“{{”或“}}”。msdn.microsoft.com/en-us/library/b1csw23d.aspx
    • 这个页面比 MSDN 更具可读性...
    • 奇怪的是,微软从 4.5 版开始从 MSDN 中删除了 {{ 符号。
    • 当我们想得到像 {name} 这样的东西作为输出时,它需要 3 个花括号作为 string.Format("{{{0}} }",名称)
    • @JacekGorgoń 任何页面都比 MSDN 更具可读性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多