鉴于此:
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);
?
一个参数可以指定多次。用这个代替:
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);
使用{0}
两次:
string msg = string.Format(
"Duckbill {0} Platypus has not been loaded. Fetch Duckbill {0}'s Platypus then continue.",
userDuckbill);
第二个代码示例将产生FormatException
,其中包含以下消息:
索引(从零开始)必须大于或等于零且小于实参列表的大小。
因此,无论何时使用{n}
,在格式字符串之后必须至少有n
参数。然而,拥有超过n
将是无用的。