Строка C#. Формат args

31
задан Brian Genisio 16 September 2009 в 16:52
поделиться

7 ответов

Your first example should work fine, provided there are at least two objects in the array args.

object[] args = new object[] { "Alice", 2 };
str = String.Format("Her name is {0} and she's {1} years old", args);
78
ответ дан 27 November 2019 в 21:26
поделиться

I'm not sure what you're asking, but either of those should work, considering that one of the signatures for the String.Format() function is

Public Shared Function Format(ByVal format As String, ByVal ParamArray args() As Object) As String

More junk I copied from Visual Studio:

Summary: Replaces the format item in a specified System.String with the text equivalent of the value of a corresponding System.Object instance in a specified array.

Parameters: format: A composite format string. args: An System.Object array containing zero or more objects to format.

Return Values: A copy of format in which the format items have been replaced by the System.String equivalent of the corresponding instances of System.Object in args.

Exceptions: System.ArgumentNullException: format or args is null. System.FormatException: format is invalid. -or- The number indicating an argument to format is less than zero, or greater than or equal to the length of the args array.

-- Oops on the VB, but you get the point.

3
ответ дан 27 November 2019 в 21:26
поделиться

It should work just the way you want it to. The String class has the following Format method definition:

public static string Format(string format, params object[] args);

Seeing as how the "args" in your example is an array of objects, it should fit right in.

14
ответ дан 27 November 2019 в 21:26
поделиться
str = String.Format("Her name is {0} and she's {1} years old", args);

Should work when args is of type object[].

2
ответ дан 27 November 2019 в 21:26
поделиться

Both your examples do the same thing - String.Format has an overload which accepts an object[] instead of specifying each argument separately.

2
ответ дан 27 November 2019 в 21:26
поделиться

Did you even try the first line? Did you see that it should work the same as the second?

1
ответ дан 27 November 2019 в 21:26
поделиться

Your second code-block would do what I think you are trying to accomplish.

string.Format("Hello {0}, {1} and {2}", new object[] { "World", "Foo", "Bar" });
1
ответ дан 27 November 2019 в 21:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: