string.Format fails at runtime with array of integers

前端 未结 7 589
囚心锁ツ
囚心锁ツ 2020-12-31 00:03

Consider string.Format() whose parameters are a string and, among others in the overload list, an object[] or many objects.

This statement

7条回答
  •  盖世英雄少女心
    2020-12-31 00:51

    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 an object[].

提交回复
热议问题