在的String.format运行失败,整数数组 [英] string.Format fails at runtime with array of integers
问题描述
考虑的String.format()
,其参数是一个字符串,其中包括在过载列表中,一个 [对象]
或多个对象。
这语句成功:
串富=的String.Format({0} {1},5,6);
为做到这一点:
[对象] myObjs =新对象[] {8,9};
字符串巴兹=的String.Format({0}和{1},myObjs;
一样字符串数组:
的String [] = myStrings新的String [] {ABC,XYZ};
字符串巴兹=的String.Format({0} {1},myStrings);
看来,整数,当单独指定,可以盒装或胁迫键入这又是强制转换为字符串对象
,
该语句将失败的运行
INT [] = myInts新INT [] {8,9};
串吧=的String.Format({0}和{1},myInts);
索引(从零开始)必须大于参数列表的大小大于或等于零且小于
块引用>
- 为什么没有或不能在int数组被强制或盒装到
[对象]
或的String []
?- 出于好奇,一个小一点的,为什么不编译器捕获此?
解决方案调用失败,同样的原因下面也将失败:
串富=的String.Format({0} {1},5);
您在
格式
指定两个论点,但只指定一个对象。由于
INT []
作为一个对象,它是该功能的完全有效的参数传递的编译器不抓住它。另外请注意,数组协方差不值类型的工作,所以你不能做的:
[对象] myInts = INT新[] {8,9};
然而,你可以逃脱:
[对象] myInts =新的字符串[] {8,9};
串吧=的String.Format({0} {1},myInts);这将工作,因为你会使用一个接受
对象
。的String.Format
超载[]Consider
string.Format()
whose parameters are a string and, among others in the overload list, anobject[]
or many objects.This statement succeeds:
string foo = string.Format("{0} {1}", 5, 6);
as does this:
object[] myObjs = new object[] {8,9}; string baz = string.Format("{0} and {1}", myObjs;
as does an array of strings:
string[] myStrings = new string[] {"abc", "xyz"}; string baz = string.Format("{0} {1}", myStrings);
It seems that the integers, when specified individually, can be boxed or coerced to type
object
, which in turn is coerced to a string.This statement fails at runtime.
int[] myInts = new int[] {8,9}; string bar = string.Format("{0} and {1}", myInts);
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
- Why doesn't or can't the int array be coerced or boxed to an
object[]
orstring[]
?- Out of a small bit of curiosity, why doesn't the compiler catch this?
解决方案The call fails with the same reason the following will also fail:
string foo = string.Format("{0} {1}", 5);
You are specifying two arguments in the
format
but only specifying one object.The compiler does not catch it because
int[]
is passed as an object which is a perfectly valid argument for the function.Also note that array covariance does not work with value types so you cannot do:
object[] myInts = new int[] {8,9};
However you can get away with:
object[] myInts = new string[] { "8", "9" }; string bar = string.Format("{0} {1}", myInts);
which would work because you would be using the
String.Format
overload that accepts anobject[]
.这篇关于在的String.format运行失败,整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!