p.c*_*ell 22 c# arrays string-formatting
考虑string.Format()哪些参数是字符串,以及在重载列表中的一个object[]或多个对象.
该声明成功:
string foo = string.Format("{0} {1}", 5, 6);
Run Code Online (Sandbox Code Playgroud)
就像这样:
object[] myObjs = new object[] {8,9};
string baz = string.Format("{0} and {1}", myObjs;
Run Code Online (Sandbox Code Playgroud)
和一串字符串一样:
string[] myStrings = new string[] {"abc", "xyz"};
string baz = string.Format("{0} {1}", myStrings);
Run Code Online (Sandbox Code Playgroud)
似乎整数,当单独指定时,可以加框或强制键入object,而后者又被强制为字符串.
此语句在运行时失败.
int[] myInts = new int[] {8,9};
string bar = string.Format("{0} and {1}", myInts);
Run Code Online (Sandbox Code Playgroud)
索引(从零开始)必须大于或等于零且小于参数列表的大小.
object[]或string[]?Joã*_*elo 25
调用失败的原因相同,以下内容也将失败:
string foo = string.Format("{0} {1}", 5);
Run Code Online (Sandbox Code Playgroud)
您在指定两个参数format但仅指定一个对象.
编译器没有捕获它,因为int[]它作为一个对象传递,这是一个完全有效的函数参数.
另请注意,数组协方差不适用于值类型,因此您无法执行以下操作:
object[] myInts = new int[] {8,9};
Run Code Online (Sandbox Code Playgroud)
但是你可以逃脱:
object[] myInts = new string[] { "8", "9" };
string bar = string.Format("{0} {1}", myInts);
Run Code Online (Sandbox Code Playgroud)
这将是有效的,因为你将使用String.Format接受的重载object[].
| 归档时间: |
|
| 查看次数: |
5618 次 |
| 最近记录: |