C# 多行逐字字符串中 string.Format 的转义参数

发布于 2024-09-26 09:20:46 字数 862 浏览 1 评论 0原文

string template = @"  
          {  
            argument1   = ""{0}"";
            argument2   = {1};  
          }";

当我使用 string.Format 将其格式化为普通字符串时,自然会出现输入字符串格式不正确的异常。我尝试按照 msdn 文档中的建议转义参数,例如“{{0}}”甚至“{{{0}}}”,但我仍然遇到相同的异常。关于如何格式化这样的字符串有什么想法吗?

谢谢!

PS[编辑] 我的原始字符串用于生成 WCAT 场景文件:

 string scenarioHeaderTemplate = @"
    scenario
    {{
       name    = ""WCAT Scenario"";
       warmup      = {0};
       duration    = {1};
       cooldown    = {2};

       default
       {
           version     = HTTP11;
           setheader
           {
               name    = ""Connection"";
               value   = ""keep-alive"";
           }
           statuscode  = 200;
           close       = ka;
       }
     }}";

如果我尝试 string.Format(scenarioHeaderTemplate, 10, 10, 10); 它会抛出异常

string template = @"  
          {  
            argument1   = ""{0}"";
            argument2   = {1};  
          }";

When I format it as a usual string with string.Format, naturally i get an exception that the input string was not in correct format. I tried escaping the arguments as it is recommended in msdn documentation, like "{{0}}" and even "{{{0}}}", but i still get the same exception. Any ideas on how to format such a string?

Thanks!

P.S.[edit] my original string is for generating a WCAT scenario file:

 string scenarioHeaderTemplate = @"
    scenario
    {{
       name    = ""WCAT Scenario"";
       warmup      = {0};
       duration    = {1};
       cooldown    = {2};

       default
       {
           version     = HTTP11;
           setheader
           {
               name    = ""Connection"";
               value   = ""keep-alive"";
           }
           statuscode  = 200;
           close       = ka;
       }
     }}";

and it throws if i try string.Format(scenarioHeaderTemplate, 10, 10, 10);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别再吹冷风 2024-10-03 09:20:46

问题在于左大括号和右大括号。您需要引用这些内容,否则 Format 会认为您正在开始参数说明符。

string template = @"   
          {{   
            argument1   = ""{0}""; 
            argument2   = {1};   
          }}"; 

The problem is the open and close braces. You need to quote those, or Format will think you're begining a parameter specifier.

string template = @"   
          {{   
            argument1   = ""{0}""; 
            argument2   = {1};   
          }}"; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文