【问题标题】:If the same val is used to replace two separate string.Format placeholders, must it be provided twice?如果用同一个val来替换两个单独的string.Format占位符,一定要提供两次吗?
【发布时间】:2013-04-12 16:32:32
【问题描述】:

鉴于此:

string msg = string.Format("Duckbill {0} Platypus has not been loaded. Fetch Duckbill {1}'s Platypus then continue.", userDuckbill, userDuckbill);

...这样做是否就足够了:

string msg = string.Format("Duckbill {0} Platypus has not been loaded. Fetch Duckbill {1}'s Platypus then continue.", userDuckbill);

?

【问题讨论】:

  • 稍作测试就可以为您节省一些在 stackoverflow 上的时间。在这种情况下,测试确实比询问更容易。
  • 不是我的情况;测试最简单的东西需要几分钟。
  • 我推荐linqpad.net
  • 我有 Linqpad,但我要么忘记了,要么不知道它适用于非 LINQ 的东西。
  • 在 LINQPad 中有这个:MessageBox.Show("This is {0}", "this"); ...并选择了“C# 语句 [s]”,当我捣碎绿色箭头 [!TM] 时,我得到“当前上下文中不存在名称 'MessageBox'”

标签: c# string.format


【解决方案1】:

您可以多次指定参数。改用这个:

string msg = string.Format("Duckbill {0} Platypus has not been loaded. Fetch Duckbill {0}'s Platypus then continue.", userDuckbill);

official documentation 有几个这样的例子。这只是一个:

  string formatString = "    {0,10} ({0,8:X8})\n" + 
                        "And {1,10} ({1,8:X8})\n" + 
                        "  = {2,10} ({2,8:X8})";
  int value1 = 16932;
  int value2 = 15421;
  string result = String.Format(formatString, value1, value2, value1 & value2);

【讨论】:

    【解决方案2】:

    使用{0} 两次:

    string msg = string.Format(
        "Duckbill {0} Platypus has not been loaded. Fetch Duckbill {0}'s Platypus then continue.",
        userDuckbill);
    

    您的第二个代码示例将生成带有以下消息的FormatException

    索引(从零开始)必须大于或等于零且小于 参数列表的大小。

    因此,无论何时使用{n},格式字符串后都必须至少有n 参数。但是,拥有多个 n 将毫无用处。

    【讨论】:

      猜你喜欢
      • 2016-09-18
      • 2012-05-07
      • 2016-03-13
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 2021-06-19
      相关资源
      最近更新 更多