5

鉴于这种:

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);

?

4

2 回答 2

20

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

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

官方文档有几个这样的例子。这里只有一个:

  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);
于 2013-04-12T16:33:04.037 回答
4

使用{0}两次:

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

您的第二个代码示例将产生FormatException以下消息:

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

因此,无论何时使用,格式字符串后{n}都必须至少有参数。n然而,拥有更多n是无用的。

于 2013-04-12T16:33:14.727 回答