String.Format String.Format String.Format String.Format Method

定義

根據指定的格式將物件的值轉換為字串,並將它們插入到另一個字串。Converts the value of objects to strings based on the formats specified and inserts them into another string.

如果您不熟悉 String.Format 方法,請參閱 String.Format 方法入門一節以取得快速概觀。If you are new to the String.Format method, see the Get started with the String.Format method section for a quick overview.

如需 String.Format 方法的一般文件,請參閱備註一節。See the Remarks section for general documentation for the String.Format method.

多載

Format(String, Object) Format(String, Object) Format(String, Object) Format(String, Object)

以指定物件的字串表示,取代字串中的一或多個格式項目。Replaces one or more format items in a string with the string representation of a specified object.

Format(String, Object[]) Format(String, Object[]) Format(String, Object[]) Format(String, Object[])

以指定陣列中對應物件的字串表示,取代指定之字串中的格式項目。Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.

Format(IFormatProvider, String, Object) Format(IFormatProvider, String, Object) Format(IFormatProvider, String, Object) Format(IFormatProvider, String, Object)

以對應物件的字串表示,取代指定之字串中的一或多個格式項目。Replaces the format item or items in a specified string with the string representation of the corresponding object. 參數提供特定文化特性格式資訊。A parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[])

以指定陣列中對應物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representations of corresponding objects in a specified array. 參數提供特定文化特性格式資訊。A parameter supplies culture-specific formatting information.

Format(String, Object, Object) Format(String, Object, Object) Format(String, Object, Object) Format(String, Object, Object)

以兩個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of two specified objects.

Format(IFormatProvider, String, Object, Object) Format(IFormatProvider, String, Object, Object) Format(IFormatProvider, String, Object, Object) Format(IFormatProvider, String, Object, Object)

以兩個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of two specified objects. 參數提供特定文化特性格式資訊。A parameter supplies culture-specific formatting information.

Format(String, Object, Object, Object) Format(String, Object, Object, Object) Format(String, Object, Object, Object) Format(String, Object, Object, Object)

以三個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of three specified objects.

Format(IFormatProvider, String, Object, Object, Object) Format(IFormatProvider, String, Object, Object, Object) Format(IFormatProvider, String, Object, Object, Object) Format(IFormatProvider, String, Object, Object, Object)

以三個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of three specified objects. 參數提供特定文化特性格式資訊。An parameter supplies culture-specific formatting information.

範例

呼叫的數個範例Format方法透過相互穿插備註一節。Numerous examples that call the Format method are interspersed through the Remarks section of this article.

注意

本文中的某些 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。Some of the C# examples in this article run in the Try.NET inline code runner and playground. 請選取 [執行] 按鈕 (若該按鈕存在) 以在互動式視窗中執行範例。When present, select the Run button to run an example in an interactive window. 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。Once you execute the code, you can modify it and run the modified code by selecting Run again. 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

您也可以下載一組完整的String.Format範例中,也就是包含適用於 C# 的.NET Core 2.0 專案適用於 Visual Basic.NET Core 2.0 專案,從dotnet /範例 GitHub 儲存機制You can also download a complete set of String.Format examples, which are included a .NET Core 2.0 project for C# and a .NET Core 2.0 project for Visual Basic, from the dotnet/samples GitHub repository.

以下是一些文章中隨附的範例:The following are some of the examples included in the article:

建立格式字串Create a format string

插入字串Inserting a string
格式項目The format item
具有相同索引的格式項目Format items that have the same index

控制格式化的輸出Control formatted output

控制格式Controlling formatting
控制間距Controlling spacing
控制對齊方式Controlling alignment
控制數目的整數位數Controlling the number of integral digits
控制的位數,小數分隔符號之後的Controlling the number of digits after the decimal separator
在結果字串中包括常值大括號Including literal braces in a result string

進行區分文化特性的格式字串Make format strings culture-sensitive

區分文化特性格式Culture-sensitive formatting

自訂格式化作業Customize the formatting operation

自訂格式化作業A custom formatting operation
截距,提供者和羅馬數字格式器An intercept provider and Roman numeral formatter

備註

重要

請不要呼叫 String.Format 方法或使用複合格式字串,您可以使用「內插字串」 (如果您的語言支援它們的話)。Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. 內插字串是包含「插入運算式」 的字串。An interpolated string is a string that contains interpolated expressions. 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. 如需詳細資訊,請參閱內插字串 (C# 參考)內插字串 (Visual Basic 參考)For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

本節內容:In this section:

String.Format 方法入門 Get started with the String.Format method
我呼叫的方法? Which method do I call?
Format 方法簡介 The Format method in brief
格式項目 The Format item
引數格式化的方式 How arguments are formatted
具有相同索引的格式項目 Format items that have the same index
格式設定和文化特性 Formatting and culture
自訂格式化作業 Custom formatting operations
String.Format Q & AString.Format Q & A

String.Format 方法入門Get started with the String.Format method

使用String.Format如果您需要將物件、 變數或運算式的值插入至另一個字串。Use String.Format if you need to insert the value of an object, variable, or expression into another string. 例如,您可以在其中插入的值Decimal為字串,以顯示給使用者以單一字串值:For example, you can insert the value of a Decimal value into a string to display it to the user as a single string:

Decimal pricePerOunce = (Decimal)17.36;
String^ s = String::Format("The current price is {0} per ounce.",
                           pricePerOunce);
// Result: The current price is 17.36 per ounce.
Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0} per ounce.",
                         pricePerOunce);
Console.WriteLine(s);
// Result: The current price is 17.36 per ounce.
Dim pricePerOunce As Decimal = 17.36d
Dim s As String = String.Format("The current price is {0} per ounce.",
                                pricePerOunce)
' Result: The current price is 17.36 per ounce.

您可以控制該值格式:And you can control that value's formatting:

Decimal pricePerOunce = (Decimal)17.36;
String^ s = String::Format("The current price is {0:C2} per ounce.",
                           pricePerOunce);
// Result if current culture is en-US:
//      The current price is $17.36 per ounce.
Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0:C2} per ounce.",
                         pricePerOunce);
Console.WriteLine(s);
// Result if current culture is en-US:
//      The current price is $17.36 per ounce.
Dim pricePerOunce As Decimal = 17.36d
Dim s As String = String.Format("The current price is {0:C2} per ounce.",
                                pricePerOunce)
' Result if current culture is en-US:
'      The current price is $17.36 per ounce.

除了格式設定,您也可以控制對齊及間距。Besides formatting, you can also control alignment and spacing.

插入字串Inserting a string

String.Format 開始使用的格式字串,後面接著一個或多個物件會轉換為字串,並插入格式字串中的指定位置的運算式。String.Format starts with a format string, followed by one or more objects or expressions that will be converted to strings and inserted at a specified place in the format string. 例如:For example:

Decimal temp = (Decimal)20.4;
String^ s = String::Format("The temperature is {0}°C.", temp);
Console::WriteLine(s);
// Displays 'The temperature is 20.4°C.'
decimal temp = 20.4m;
string s = String.Format("The temperature is {0}°C.", temp);
Console.WriteLine(s);
// Displays 'The temperature is 20.4°C.'
Dim temp As Decimal = 20.4d
Dim s As String = String.Format("The temperature is {0}°C.", temp)
Console.WriteLine(s)
' Displays 'The temperature is 20.4°C.'

{0}格式字串是一個格式項目。The {0} in the format string is a format item. 0 為其字串值會在該位置插入物件的索引。0 is the index of the object whose string value will be inserted at that position. (索引從 0 開始。)如果要插入的物件不是字串,其ToString呼叫方法,將它轉換成其中一個,再將其插入結果字串中。(Indexes start at 0.) If the object to be inserted is not a string, its ToString method is called to convert it to one before inserting it in the result string.

在 [物件] 清單中會使用兩個格式項目和兩個物件的另一個範例如下︰Here's another example that uses two format items and two objects in the object list:

String^ s = String::Format("At {0}, the temperature is {1}°C.",
                           DateTime::Now, 20.4);
// Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
string s = String.Format("At {0}, the temperature is {1}°C.",
                         DateTime.Now, 20.4);
Console.WriteLine(s);
// Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
Dim s As String = String.Format("At {0}, the temperature is {1}°C.",
                                Date.Now, 20.4)
' Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'

您可以有多個格式項目,並想與您的 [物件] 清單中的多個物件,只要每個格式項目的索引物件清單中有相符的物件。You can have as many format items and as many objects in the object list as you want, as long as the index of every format item has a matching object in the object list. 您也不需要擔心有關哪個多載您呼叫;編譯器會選取適合您。You also don't have to worry about which overload you call; the compiler will select the appropriate one for you.

控制格式Controlling formatting

您可以遵循以格式字串來控制如何格式化物件的格式項目中的索引。You can follow the index in a format item with a format string to control how an object is formatted. 比方說, {0:d} "d"格式字串套用至物件清單中的第一個物件。For example, {0:d} applies the "d" format string to the first object in the object list. 以下是具有單一物件的範例,以及兩個格式項目:Here is an example with a single object and two format items:

String^ s = String::Format("It is now {0:d} at {0:t}",
                           DateTime::Now);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
string s = String.Format("It is now {0:d} at {0:t}", DateTime.Now);
Console.WriteLine(s);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
Dim s As String = String.Format("It is now {0:d} at {0:t}",
                                Date.Now)
' Output similar to: 'It is now 4/10/2015 at 10:04 AM'

幾個型別支援的格式字串,包括所有數字類型 (兩者標準自訂格式字串),所有日期和時間 (同時標準自訂格式字串) 和時間間隔 (同時標準自訂格式字串),所有的列舉型別列舉型別,並GuidA number of types support format strings, including all numeric types (both standard and custom format strings), all dates and times (both standard and custom format strings) and time intervals (both standard and custom format strings), all enumeration types enumeration types, and GUIDs. 您也可以將格式字串的支援加入自己的型別中。You can also add support for format strings to your own types.

控制間距Controlling spacing

您可以定義使用下列語法會插入至結果字串的字串寬度{0,12},其插入 12 個字元的字串。You can define the width of the string that is inserted into the result string by using syntax such as {0,12}, which inserts a 12-character string. 在此情況下,第一個物件的字串表示是靠右對齊在 12 個字元的欄位。In this case, the string representation of the first object is right-aligned in the 12-character field. (如果第一個物件的字串表示的長度超過 12 個字元,不過,慣用的欄位寬度會被忽略,和整個字串插入至結果字串。)(If the string representation of the first object is more than 12 characters in length, though, the preferred field width is ignored, and the entire string is inserted into the result string.)

下列範例定義了 6 個字元的欄位來容納字串 「 年 」 和部份年的字串,以及 15 個字元的欄位來容納字串 「 母體擴展 」 以及一些人口資料。The following example defines a 6-character field to hold the string "Year" and some year strings, as well as an 15-character field to hold the string "Population" and some population data. 請注意,字元會靠右對齊欄位中。Note that the characters are right-aligned in the field.

array<int>^ years = { 2013, 2014, 2015 };
array<int>^ population = { 1025632, 1105967, 1148203 };
StringBuiler^ sb = gcnew StringBuilder();
sb->Append(String::Format("{0,6} {1,15}\n\n", "Year", "Population"));
for(int index = 0; index < years->Length; index++)
   sb->AppendFormat("{0,6} {1,15:N0}\n",
                    years[index], population[index]);
// Result:
//      Year      Population
//
//      2013       1,025,632
//      2014       1,105,967
//      2015       1,148,203
int[] years = { 2013, 2014, 2015 };
int[] population = { 1025632, 1105967, 1148203 };
var sb = new System.Text.StringBuilder();
sb.Append(String.Format("{0,6} {1,15}\n\n", "Year", "Population"));
for (int index = 0; index < years.Length; index++)
   sb.Append(String.Format("{0,6} {1,15:N0}\n", years[index], population[index]));

Console.WriteLine(sb);

// Result:
//      Year      Population
//
//      2013       1,025,632
//      2014       1,105,967
//      2015       1,148,203
Dim years() As Integer = { 2013, 2014, 2015 }
Dim population() As Integer  = { 1025632, 1105967, 1148203 }
Dim sb As New StringBuilder()
sb.Append(String.Format("{0,6} {1,15}{2}{2}",
                        "Year", "Population", vbCrLf))
For index As Integer = 0 To years.Length - 1
   sb.AppendFormat("{0,6} {1,15:N0}{2}",
                   years(index), population(index), vbCrLf)
Next
' Result:
'      Year      Population
'
'      2013       1,025,632
'      2014       1,105,967
'      2015       1,148,203

控制對齊方式Controlling alignment

根據預設,字串會靠右對齊其欄位內如果您指定欄位寬度。By default, strings are right-aligned within their field if you specify a field width. 若要靠左對齊欄位中的字串,您前加上負號,將欄位寬度這類{0,-12}定義 12 個字元,靠左對齊的欄位。To left-align strings in a field, you preface the field width with a negative sign, such as {0,-12} to define a 12-character left-aligned field.

下列範例是類似於上一個,不同之處在於它靠左對齊的標籤和資料。The following example is similar to the previous one, except that it left-aligns both labels and data.

array<int>^ years = { 2013, 2014, 2015 };
array<int>^ population = { 1025632, 1105967, 1148203 };
String^ s = String::Format("{0,-10} {1,-10}\n\n", "Year", "Population");
for(int index = 0; index < years->Length; index++)
   s += String::Format("{0,-10} {1,-10:N0}\n",
                      years[index], population[index]);
// Result:
//    Year       Population
//
//    2013       1,025,632
//    2014       1,105,967
//    2015       1,148,203
int[] years = { 2013, 2014, 2015 };
int[] population = { 1025632, 1105967, 1148203 };
String s = String.Format("{0,-10} {1,-10}\n\n", "Year", "Population");
for(int index = 0; index < years.Length; index++)
   s += String.Format("{0,-10} {1,-10:N0}\n",
                      years[index], population[index]);
Console.WriteLine($"\n{s}");
// Result:
//    Year       Population
//
//    2013       1,025,632
//    2014       1,105,967
//    2015       1,148,203
Dim years() As Integer = { 2013, 2014, 2015 }
Dim population() As Integer  = { 1025632, 1105967, 1148203 }
Dim s As String = String.Format("{0,-10} {1,-10}{2}{2}",
                                "Year", "Population", vbCrLf)
For index As Integer = 0 To years.Length - 1
   s += String.Format("{0,-10} {1,-10:N0}{2}",
                      years(index), population(index), vbCrLf)
Next
' Result:
'    Year       Population
'
'    2013       1,025,632
'    2014       1,105,967
'    2015       1,148,203

String.Format 利用複合格式功能。String.Format makes use of the composite formatting feature. 如需詳細資訊,請參閱複合格式設定For more information, see Composite Formatting.

我呼叫的方法?Which method do I call?

To CallCall
使用目前的文化特性的慣例格式化一個或多個物件。Format one or more objects by using the conventions of the current culture. 除了包含的多載provider參數,其餘Format多載包含String參數後面接著一或多個物件的參數。Except for the overloads that include a provider parameter, the remaining Format overloads include a String parameter followed by one or more object parameters. 基於這個原因,您不需要判斷哪些Format您想要呼叫的多載。Because of this, you don't have to determine which Format overload you intend to call. 您的語言編譯器會選取從沒有多載中的適當多載provider參數,根據您的引數清單。Your language compiler selects the appropriate overload from among the overloads that don't have a provider parameter, based on your argument list. 例如,如果您的引數清單有五個引數,編譯器會呼叫Format(String, Object[])方法。For example, if your argument list has five arguments, the compiler calls the Format(String, Object[]) method.
使用特定文化特性的慣例格式化一個或多個物件。Format one or more objects by using the conventions of a specific culture. 每個Format開頭的多載provider後面接著參數String參數和一個或多個物件的參數。Each Format overload that begins with a provider parameter is followed by a String parameter and one or more object parameters. 基於這個原因,您不需要判斷哪一項特定Format您想要呼叫的多載。Because of this, you don't have to determine which specific Format overload you intend to call. 您的語言編譯器會選取具有多載,從適當的多載provider參數,根據您的引數清單。Your language compiler selects the appropriate overload from among the overloads that have a provider parameter, based on your argument list. 例如,如果您的引數清單有五個引數,編譯器會呼叫Format(IFormatProvider, String, Object[])方法。For example, if your argument list has five arguments, the compiler calls the Format(IFormatProvider, String, Object[]) method.
不論是透過執行自訂的格式設定操作ICustomFormatter實作或IFormattable實作。Perform a custom formatting operation either with an ICustomFormatter implementation or an IFormattable implementation. 任何具有四個多載provider參數。Any of the four overloads with a provider parameter. 編譯器會選擇適當的多載,從多載provider參數,根據您的引數清單。The compiler selects the appropriate overload from among the overloads that have a provider parameter, based on your argument list.

Format 方法簡介The Format method in brief

每個多載Format方法會使用複合格式功能若要包含以零為起始的索引的位置,呼叫項目的格式,複合格式字串中。Each overload of the Format method uses the composite formatting feature to include zero-based indexed placeholders, called format items, in a composite format string. 在執行階段,每個格式項目會取代對應的引數在參數清單的字串表示。At run time, each format item is replaced with the string representation of the corresponding argument in a parameter list. 引數的值是否null,將格式項目會取代String.EmptyIf the value of the argument is null, the format item is replaced with String.Empty. 例如,下列呼叫來Format(String, Object, Object, Object)方法包含三個格式項目 中,格式字串{0}, {1},和{2},和包含三個項目的引數清單。For example, the following call to the Format(String, Object, Object, Object) method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items.

using namespace System;

void main()
{
   DateTime^ dat = gcnew DateTime(2012, 1, 17, 9, 30, 0); 
   String^ city = "Chicago";
   int temp = -16;
   String^ output = String::Format("At {0} in {1}, the temperature was {2} degrees.",
                                   dat, city, temp);
   Console::WriteLine(output);
}
// The example displays the following output: 
//    At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.   
DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0); 
string city = "Chicago";
int temp = -16;
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.",
                              dat, city, temp);
Console.WriteLine(output);
// The example displays output like the following:
//    At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.   
Dim dat As Date = #1/17/2012 9:30AM# 
Dim city As String = "Chicago"
Dim temp As Integer = -16
Dim output As String = String.Format("At {0} in {1}, the temperature was {2} degrees.",
                                     dat, city, temp)
Console.WriteLine(output)
' The example displays the following output:
'    At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.   

格式項目The format item

格式項目具有此語法:A format item has this syntax:

{index[,alignment][:formatString]}  

方括號表示選擇性的項目。Brackets denote optional elements. 左和右大括號是必要。The opening and closing braces are required. (包含常值的開頭或結尾大括號在格式字串中,請參閱逸出大括號一節複合格式化文章。)(To include a literal opening or closing brace in the format string, see the Escaping Braces section in the Composite Formatting article.)

比方說,若要格式化為貨幣值的格式項目可能如下所示:For example, a format item to format a currency value might appear like this:

String::Format("{0,-10:C}", (Decimal) 126347.89);         
var value = String.Format("{0,-10:C}", 126347.89m);         
Console.WriteLine(value);
String.Format("{0,-10:C}", 126347.89d)        

格式項目具有下列項目:A format item has the following elements:

indexindex
起始的索引,要為其字串表示的引數包含在字串中的這個位置。The zero-based index of the argument whose string representation is to be included at this position in the string. 如果這個引數是null,空字串會包含在字串中的這個位置。If this argument is null, an empty string will be included at this position in the string.

alignmentalignment
選擇性。Optional. 帶正負號的整數,指出欄位的總長度的引數會插入和它會靠右對齊 (正整數),或靠左對齊 (負整數)。A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). 如果您省略對齊,不含前置或尾端空格的欄位會插入對應的引數的字串表示。If you omit alignment, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces.

如果的值對齊是要插入的引數的長度小於對齊會被忽略,並用引數的字串表示的長度當做欄位寬度。If the value of alignment is less than the length of the argument to be inserted, alignment is ignored and the length of the string representation of the argument is used as the field width.

formatStringformatString
選擇性。Optional. 字串,指定對應的引數的結果字串的格式。A string that specifies the format of the corresponding argument's result string. 如果您省略formatString,對應的引數的無參數ToString呼叫方法來產生它的字串表示。If you omit formatString, the corresponding argument's parameterless ToString method is called to produce its string representation. 如果您指定formatString,將格式項目所參考的引數必須實作IFormattable介面。If you specify formatString, the argument referenced by the format item must implement the IFormattable interface. 支援格式字串的類型包括:Types that support format strings include:

不過,請注意,可以實作任何自訂的型別IFormattable擴充現有的類型或IFormattable實作。However, note that any custom type can implement IFormattable or extend an existing type's IFormattable implementation.

下列範例會使用alignmentformatString来產生格式化的輸出引數。The following example uses the alignment and formatString arguments to produce formatted output.

using namespace System;

void main()
{
   // Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
   array<Tuple<String^, DateTime, int, DateTime, int>^>^ cities = gcnew array<Tuple<String^, DateTime, int, DateTime, int>^> 
         { gcnew Tuple<String^, DateTime, int, DateTime, int>("Los Angeles", DateTime(1940, 1, 1), 1504277, 
                        DateTime(1950, 1, 1), 1970358),
         gcnew Tuple<String^, DateTime, int, DateTime, int>("New York", DateTime(1940, 1, 1), 7454995, 
                        DateTime(1950, 1, 1), 7891957),  
         gcnew Tuple<String^, DateTime, int, DateTime, int>("Chicago", DateTime(1940, 1, 1), 3396808, 
                        DateTime(1950, 1, 1), 3620962),  
         gcnew Tuple<String^, DateTime, int, DateTime, int>("Detroit", DateTime(1940, 1, 1), 1623452, 
                        DateTime(1950, 1, 1), 1849568) };

   // Display header
   String^ header = String::Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
                                   "City", "Year", "Population", "Change (%)");
   Console::WriteLine(header);
   String^ output;      
   for each (Tuple<String^, DateTime, int, DateTime, int>^ city in cities) {
      output = String::Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                              city->Item1, city->Item2, city->Item3, city->Item4, city->Item5,
                              (city->Item5 - city->Item3)/ (double)city->Item3);
      Console::WriteLine(output);
   }
}
// The example displays the following output:
//    City            Year  Population    Year  Population    Change (%)
//    
//    Los Angeles     1940   1,504,277    1950   1,970,358        31.0 %
//    New York        1940   7,454,995    1950   7,891,957         5.9 %
//    Chicago         1940   3,396,808    1950   3,620,962         6.6 %
//    Detroit         1940   1,623,452    1950   1,849,568        13.9 %
// Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
Tuple<string, DateTime, int, DateTime, int>[] cities = 
    { Tuple.Create("Los Angeles", new DateTime(1940, 1, 1), 1504277, 
                   new DateTime(1950, 1, 1), 1970358),
      Tuple.Create("New York", new DateTime(1940, 1, 1), 7454995, 
                   new DateTime(1950, 1, 1), 7891957),  
      Tuple.Create("Chicago", new DateTime(1940, 1, 1), 3396808, 
                   new DateTime(1950, 1, 1), 3620962),  
      Tuple.Create("Detroit", new DateTime(1940, 1, 1), 1623452, 
                   new DateTime(1950, 1, 1), 1849568) };

// Display header
var header = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
                              "City", "Year", "Population", "Change (%)");
Console.WriteLine(header);
foreach (var city in cities) {
   var output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                          city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                          (city.Item5 - city.Item3)/ (double)city.Item3);
   Console.WriteLine(output);
}
// The example displays the following output:
//    City            Year  Population    Year  Population    Change (%)
//  
//    Los Angeles     1940   1,504,277    1950   1,970,358        31.0 %
//    New York        1940   7,454,995    1950   7,891,957         5.9 %
//    Chicago         1940   3,396,808    1950   3,620,962         6.6 %
//    Detroit         1940   1,623,452    1950   1,849,568        13.9 %
Module Example
   Public Sub Main()
      ' Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
      Dim cities()  = _
          { Tuple.Create("Los Angeles", #1/1/1940#, 1504277, #1/1/1950#, 1970358),
            Tuple.Create("New York", #1/1/1940#, 7454995, #1/1/1950#, 7891957),  
            Tuple.Create("Chicago", #1/1/1940#, 3396808, #1/1/1950#, 3620962),  
            Tuple.Create("Detroit", #1/1/1940#, 1623452, #1/1/1950#, 1849568) }

      ' Display header
      Dim header As String = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}",
                                           "City", "Year", "Population", "Change (%)")
      Console.WriteLine(header)
      Console.WriteLine()
      For Each city In cities
         Dim output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                                city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                                (city.Item5 - city.Item3)/city.Item3)
         Console.WriteLine(output)
      Next
   End Sub
End Module
' The example displays the following output:
'    City            Year  Population    Year  Population    Change (%)
'    
'    Los Angeles     1940   1,504,277    1950   1,970,358        31.0 %
'    New York        1940   7,454,995    1950   7,891,957         5.9 %
'    Chicago         1940   3,396,808    1950   3,620,962         6.6 %
'    Detroit         1940   1,623,452    1950   1,849,568        13.9 %

引數格式化的方式How arguments are formatted

格式項目會依序處理,從字串的開頭。Format items are processed sequentially from the beginning of the string. 每個格式項目有對應至方法的引數清單中之物件的索引。Each format item has an index that corresponds to an object in the method's argument list. Format方法會擷取引數,並衍生其字串表示,如下所示:The Format method retrieves the argument and derives its string representation as follows:

如需範例,會呼叫攔截ICustomFormatter.Format方法,並可讓您查看哪些資訊Format方法傳遞至格式的方法,以便在複合格式字串中,每個格式項目請參閱範例:截距,提供者和羅馬字母數字格式子For an example that intercepts calls to the ICustomFormatter.Format method and allows you to see what information the Format method passes to a formatting method for each format item in a composite format string, see Example: An intercept provider and Roman numeral formatter.

如需詳細資訊,請參閱 < 處理順序一節複合格式化文章。For more information, see the Processing Order section in the Composite Formatting article.

具有相同索引的格式項目Format items that have the same index

Format方法會擲回FormatException索引的索引項目是否大於或等於引數清單中的引數的例外狀況。The Format method throws a FormatException exception if the index of an index item is greater than or equal to the number of arguments in the argument list. 不過,format可以包含有引數,超過的格式項目,為多個格式項目具有相同的索引。However, format can include more format items than there are arguments, as long as multiple format items have the same index. 在呼叫Format(String, Object)在下列範例中,引數清單的方法有單一引數,但在格式字串包含兩個格式項目: 一個會顯示數字的十進位值與另一個則顯示其十六進位值。In the call to the Format(String, Object) method in following example, the argument list has a single argument, but the format string includes two format items: one displays the decimal value of a number, and the other displays its hexadecimal value.

short[] values= { Int16.MinValue, -27, 0, 1042, Int16.MaxValue };
Console.WriteLine("{0,10}  {1,10}\n", "Decimal", "Hex");
foreach (short value in values)
{
   string formatString = String.Format("{0,10:G}: {0,10:X}", value);
   Console.WriteLine(formatString);
}   
// The example displays the following output:
//       Decimal         Hex
//    
//        -32768:       8000
//           -27:       FFE5
//             0:          0
//          1042:        412
//         32767:       7FFF
Module Example
   Public Sub Main()
      Dim values() As Short = { Int16.MinValue, -27, 0, 1042, Int16.MaxValue }
      Console.WriteLine("{0,10}  {1,10}", "Decimal", "Hex")
      Console.WriteLine()
      For Each value As Short In values
         Dim formatString As String = String.Format("{0,10:G}: {0,10:X}", value)
         Console.WriteLine(formatString)
      Next        
   End Sub
End Module
' The example displays the following output:
'       Decimal         Hex
'    
'        -32768:       8000
'           -27:       FFE5
'             0:          0
'          1042:        412
'         32767:       7FFF

格式設定和文化特性Formatting and culture

一般而言,引數清單中的物件會轉換成其字串表示法傳回使用目前的文化特性的慣例CultureInfo.CurrentCulture屬性。Generally, objects in the argument list are converted to their string representations by using the conventions of the current culture, which is returned by the CultureInfo.CurrentCulture property. 您可以控制此行為,藉由呼叫其中一個多載Format,其中包含provider參數。You can control this behavior by calling one of the overloads of Format that includes a provider parameter. provider參數是IFormatProvider實作,提供自訂和特定文化特性格式資訊用來調節格式處理。The provider parameter is an IFormatProvider implementation that supplies custom and culture-specific formatting information that is used to moderate the formatting process.

IFormatProvider介面具有單一成員, GetFormat,它會負責傳回提供格式設定資訊的物件。The IFormatProvider interface has a single member, GetFormat, which is responsible for returning the object that provides formatting information. .NET 有三個IFormatProvider實作,以提供特定文化特性:.NET has three IFormatProvider implementations that provide culture-specific formatting:

自訂格式化作業Custom formatting operations

您也可以呼叫任何多載Format方法具有provider型別的參數IFormatProvider執行自訂的格式設定作業。You can also call the any of the overloads of the Format method that have a provider parameter of type IFormatProvider to perform custom formatting operations. 比方說,您可以格式化整數作為身分證號碼或電話號碼。For example, you could format an integer as an identification number or as a telephone number. 若要執行自訂的格式,您provider引數必須同時實作IFormatProviderICustomFormatter介面。To perform custom formatting, your provider argument must implement both the IFormatProvider and ICustomFormatter interfaces. Format傳遞給方法ICustomFormatter做為實作provider引數,Format方法呼叫其IFormatProvider.GetFormat實作,並要求型別的物件ICustomFormatterWhen the Format method is passed an ICustomFormatter implementation as the provider argument, the Format method calls its IFormatProvider.GetFormat implementation and requests an object of type ICustomFormatter. 然後它會呼叫傳回ICustomFormatter物件的Format方法來格式化複合字串中的每個格式項目傳遞給它。It then calls the returned ICustomFormatter object's Format method to format each format item in the composite string passed to it.

如需有關如何提供自訂格式解決方案的詳細資訊,請參閱How to:定義和使用自訂數值格式提供者ICustomFormatterFor more information about providing custom formatting solutions, see How to: Define and Use Custom Numeric Format Providers and ICustomFormatter. 如需將整數轉換為格式化的自訂數字的範例,請參閱範例:自訂的格式設定操作For an example that converts integers to formatted custom numbers, see Example: A custom formatting operation. 如需將不帶正負號的位元組轉換成羅馬數字的範例,請參閱範例:截距,提供者和羅馬字母數字格式子For an example that converts unsigned bytes to Roman numerals, see Example: An intercept provider and Roman numeral formatter.

範例:自訂格式化作業Example: A custom formatting operation

這個範例會定義為以表單為 x-xxxxx-xx 的客戶帳戶編號格式的整數值的格式提供者。This example defines a format provider that formats an integer value as a customer account number in the form x-xxxxx-xx.

using namespace System;

ref class CustomerFormatter : IFormatProvider, ICustomFormatter
{
public:
   virtual Object^ GetFormat(Type^ formatType) 
   {
      if (formatType == ICustomFormatter::typeid)        
         return this; 
      else 
         return nullptr; 
   }
   
   virtual String^ Format(String^ format, 
	               Object^ arg, 
	               IFormatProvider^ formatProvider) 
   {                       
      if (! this->Equals(formatProvider))
      {
         return nullptr;
      }
      else
      {
         if (String::IsNullOrEmpty(format)) 
            format = "G";
         
         String^ customerString = arg->ToString();
         if (customerString->Length < 8)
            customerString = customerString->PadLeft(8, '0');
         
         format = format->ToUpper();
         if (format == L"G") 
               return customerString->Substring(0, 1) + "-" +
                                     customerString->Substring(1, 5) + "-" +
                                     customerString->Substring(6);
         else if (format == L"S")                          
               return customerString->Substring(0, 1) + "/" +
                                     customerString->Substring(1, 5) + "/" +
                                     customerString->Substring(6);
         else if (format == L"P")
               return customerString->Substring(0, 1) + "." +
                                     customerString->Substring(1, 5) + "." +
                                     customerString->Substring(6);
         else
               throw gcnew FormatException( 
                         String::Format("The '{0}' format specifier is not supported.", format));
         }
    }   
};

void main()
{
   int acctNumber = 79203159;
   Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0}", acctNumber));
   Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:G}", acctNumber));
   Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:S}", acctNumber));
   Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:P}", acctNumber));
   try {
      Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:X}", acctNumber));
   }
   catch (FormatException^ e) {
      Console::WriteLine(e->Message);
   }
}
// The example displays the following output:
//       7-92031-59
//       7-92031-59
//       7/92031/59
//       7.92031.59
//       The 'X' format specifier is not supported.
using System;

public class TestFormatter
{
   public static void Main()
   {
      int acctNumber = 79203159;
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:G}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:S}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:P}", acctNumber));
      try {
         Console.WriteLine(String.Format(new CustomerFormatter(), "{0:X}", acctNumber));
      }
      catch (FormatException e) {
         Console.WriteLine(e.Message);
      }
   }
}

public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType) 
   {
      if (formatType == typeof(ICustomFormatter))        
         return this; 
      else
         return null;
   }
   
   public string Format(string format, 
	                     object arg, 
	                     IFormatProvider formatProvider) 
   {                       
      if (! this.Equals(formatProvider))
      {
         return null;
      }
      else
      {
         if (String.IsNullOrEmpty(format)) 
            format = "G";
         
         string customerString = arg.ToString();
         if (customerString.Length < 8)
            customerString = customerString.PadLeft(8, '0');
         
         format = format.ToUpper();
         switch (format)
         {
            case "G":
               return customerString.Substring(0, 1) + "-" +
                                     customerString.Substring(1, 5) + "-" +
                                     customerString.Substring(6);
            case "S":                          
               return customerString.Substring(0, 1) + "/" +
                                     customerString.Substring(1, 5) + "/" +
                                     customerString.Substring(6);
            case "P":                          
               return customerString.Substring(0, 1) + "." +
                                     customerString.Substring(1, 5) + "." +
                                     customerString.Substring(6);
            default:
               throw new FormatException( 
                         String.Format("The '{0}' format specifier is not supported.", format));
         }
      }   
   }
}
// The example displays the following output:
//       7-92031-59
//       7-92031-59
//       7/92031/59
//       7.92031.59
//       The 'X' format specifier is not supported.
Module TestFormatter
   Public Sub Main()
      Dim acctNumber As Integer = 79203159
      Console.WriteLine(String.Format(New CustomerFormatter, "{0}", acctNumber))
      Console.WriteLine(String.Format(New CustomerFormatter, "{0:G}", acctNumber))
      Console.WriteLine(String.Format(New CustomerFormatter, "{0:S}", acctNumber))
      Console.WriteLine(String.Format(New CustomerFormatter, "{0:P}", acctNumber))
      Try
         Console.WriteLine(String.Format(New CustomerFormatter, "{0:X}", acctNumber))
      Catch e As FormatException
         Console.WriteLine(e.Message)
      End Try   
   End Sub
End Module

Public Class CustomerFormatter : Implements IFormatProvider, ICustomFormatter
   Public Function GetFormat(type As Type) As Object  _
                   Implements IFormatProvider.GetFormat
      If type Is GetType(ICustomFormatter) Then
         Return Me
      Else
         Return Nothing
      End If
   End Function
   
   Public Function Format(fmt As String, _
	                       arg As Object, _
	                       formatProvider As IFormatProvider) As String _
	                Implements ICustomFormatter.Format
      If Not Me.Equals(formatProvider) Then
         Return Nothing
      Else
         If String.IsNullOrEmpty(fmt) Then fmt = "G"
         
         Dim customerString As String = arg.ToString()
         if customerString.Length < 8 Then _
            customerString = customerString.PadLeft(8, "0"c)
         
         Select Case fmt
            Case "G"
               Return customerString.Substring(0, 1) & "-" & _
                                     customerString.Substring(1, 5) & "-" & _
                                     customerString.Substring(6)
            Case "S"                         
               Return customerString.Substring(0, 1) & "/" & _
                                     customerString.Substring(1, 5) & "/" & _
                                     customerString.Substring(6)
            Case "P"
               Return customerString.Substring(0, 1) & "." & _
                                     customerString.Substring(1, 5) & "." & _
                                     customerString.Substring(6)
            Case Else
               Throw New FormatException( _
                         String.Format("The '{0}' format specifier is not supported.", fmt))
         End Select                                                     
      End If   
   End Function
End Class
' The example displays the following output:
'       7-92031-59
'       7-92031-59
'       7/92031/59
'       7.92031.59
'       The 'X' format specifier is not supported.

範例:截距,提供者和羅馬數字格式器Example: An intercept provider and Roman numeral formatter

這個範例會定義自訂的格式提供者可實作ICustomFormatterIFormatProvider介面做兩件事:This example defines a custom format provider that implements the ICustomFormatter and IFormatProvider interfaces to do two things:

  • 它會顯示參數傳遞至其ICustomFormatter.Format實作。It displays the parameters passed to its ICustomFormatter.Format implementation. 這可讓我們看到哪些參數Format(IFormatProvider, String, Object[])方法將傳遞給每個物件,它會嘗試格式化自訂的格式化實作。This enables us to see what parameters the Format(IFormatProvider, String, Object[]) method is passing to the custom formatting implementation for each object that it tries to format. 當您偵錯您的應用程式,這非常有用。This can be useful when you're debugging your application.

  • 要格式化的物件是否為使用"R"標準格式字串格式化的不帶正負號的位元組值,將自訂格式器會格式化為羅馬字母數字的數字的值。If the object to be formatted is an unsigned byte value that is to be formatted by using the "R" standard format string, the custom formatter formats the numeric value as a Roman numeral.

using namespace System;
using namespace System::Globalization;

ref class InterceptProvider : IFormatProvider, ICustomFormatter
{
public:
   virtual Object^ GetFormat(Type^ formatType)
   {
      if (formatType == ICustomFormatter::typeid)   
         return this;
      else
         return nullptr;
   }
   
   virtual String^ Format(String^ format, Object^ obj, IFormatProvider^ provider) 
   {
      // Display information about method call.
      String^ formatString = format != nullptr ? format : "<null>";
      Console::WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
                        provider, obj != nullptr ? obj : "<null>", formatString);
                        
      if (obj == nullptr) return String::Empty;
            
      // If this is a byte and the "R" format string, format it with Roman numerals.
      if (obj->GetType() == Byte::typeid && formatString->ToUpper()->Equals("R")) {
         Byte value = (Byte) obj;
         int remainder;
         int result;
         String^ returnString = String::Empty;

         // Get the hundreds digit(s)
         result = Math::DivRem(value, 100, remainder);
         if (result > 0)  
            returnString = gcnew String('C', result);
         value = (Byte) remainder;
         // Get the 50s digit
         result = Math::DivRem(value, 50, remainder);
         if (result == 1)
            returnString += "L";
         value = (Byte) remainder;
         // Get the tens digit.
         result = Math::DivRem(value, 10, remainder);
         if (result > 0)
            returnString += gcnew String('X', result);
         value = (Byte) remainder; 
         // Get the fives digit.
         result = Math::DivRem(value, 5, remainder);
         if (result > 0)
            returnString += "V";
         value = (Byte) remainder;
         // Add the ones digit.
         if (remainder > 0) 
            returnString += gcnew String('I', remainder);
         
         // Check whether we have too many X characters.
         int pos = returnString->IndexOf("XXXX");
         if (pos >= 0) {
            int xPos = returnString->IndexOf("L"); 
            if ((xPos >= 0) & (xPos == pos - 1))
               returnString = returnString->Replace("LXXXX", "XC");
            else
               returnString = returnString->Replace("XXXX", "XL");   
         }
         // Check whether we have too many I characters
         pos = returnString->IndexOf("IIII");
         if (pos >= 0)
            if (returnString->IndexOf("V") >= 0)
               returnString = returnString->Replace("VIIII", "IX");
            else
               returnString = returnString->Replace("IIII", "IV");    

         return returnString; 
      }   

      // Use default for all other formatting.
      if (obj->GetType() == IFormattable::typeid)
         return ((IFormattable^) obj)->ToString(format, CultureInfo::CurrentCulture);
      else
         return obj->ToString();
   }
};

void main()
{
   int n = 10;
   double value = 16.935;
   DateTime day = DateTime::Now;
   InterceptProvider^ provider = gcnew InterceptProvider();
   Console::WriteLine(String::Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day));
   Console::WriteLine(String::Format(provider, "{0}: {1:F}\n", "Today: ", 
                                    (DayOfWeek) DateTime::Now.DayOfWeek));
   Console::WriteLine(String::Format(provider, "{0:X}, {1}, {2}\n", 
                                    (Byte) 2, (Byte) 12, (Byte) 199));
   Console::WriteLine(String::Format(provider, "{0:R}, {1:R}, {2:R}\n", 
                                    (Byte) 2, (Byte) 12, (Byte) 199));
}
// The example displays the following output:
//    Provider: InterceptProvider, Object: 10, Format String: N0
//    Provider: InterceptProvider, Object: 16.935, Format String: C2
//    Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
//    10: $16.94 on 1/31/2013
//    
//    Provider: InterceptProvider, Object: Today: , Format String: <null>
//    Provider: InterceptProvider, Object: Thursday, Format String: F
//    Today: : Thursday
//    
//    Provider: InterceptProvider, Object: 2, Format String: X
//    Provider: InterceptProvider, Object: 12, Format String: <null>
//    Provider: InterceptProvider, Object: 199, Format String: <null>
//    2, 12, 199
//    
//    Provider: InterceptProvider, Object: 2, Format String: R
//    Provider: InterceptProvider, Object: 12, Format String: R
//    Provider: InterceptProvider, Object: 199, Format String: R
//    II, XII, CXCIX
using System;
using System.Globalization;

public class InterceptProvider : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }
   
   public string Format(String format, Object obj, IFormatProvider provider) 
   {
      // Display information about method call.
      string formatString = format ?? "<null>";
      Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
                        provider.GetType().Name, obj ?? "<null>", formatString);
                        
      if (obj == null) return String.Empty;
            
      // If this is a byte and the "R" format string, format it with Roman numerals.
      if (obj is Byte && formatString.ToUpper().Equals("R")) {
         Byte value = (Byte) obj;
         int remainder;
         int result;
         String returnString = String.Empty;

         // Get the hundreds digit(s)
         result = Math.DivRem(value, 100, out remainder);
         if (result > 0)  
            returnString = new String('C', result);
         value = (Byte) remainder;
         // Get the 50s digit
         result = Math.DivRem(value, 50, out remainder);
         if (result == 1)
            returnString += "L";
         value = (Byte) remainder;
         // Get the tens digit.
         result = Math.DivRem(value, 10, out remainder);
         if (result > 0)
            returnString += new String('X', result);
         value = (Byte) remainder; 
         // Get the fives digit.
         result = Math.DivRem(value, 5, out remainder);
         if (result > 0)
            returnString += "V";
         value = (Byte) remainder;
         // Add the ones digit.
         if (remainder > 0) 
            returnString += new String('I', remainder);
         
         // Check whether we have too many X characters.
         int pos = returnString.IndexOf("XXXX");
         if (pos >= 0) {
            int xPos = returnString.IndexOf("L"); 
            if (xPos >= 0 & xPos == pos - 1)
               returnString = returnString.Replace("LXXXX", "XC");
            else
               returnString = returnString.Replace("XXXX", "XL");   
         }
         // Check whether we have too many I characters
         pos = returnString.IndexOf("IIII");
         if (pos >= 0)
            if (returnString.IndexOf("V") >= 0)
               returnString = returnString.Replace("VIIII", "IX");
            else
               returnString = returnString.Replace("IIII", "IV");    

         return returnString; 
      }   

      // Use default for all other formatting.
      if (obj is IFormattable)
         return ((IFormattable) obj).ToString(format, CultureInfo.CurrentCulture);
      else
         return obj.ToString();
   }
}

public class Example
{
   public static void Main()
   {
      int n = 10;
      double value = 16.935;
      DateTime day = DateTime.Now;
      InterceptProvider provider = new InterceptProvider();
      Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day));
      Console.WriteLine(String.Format(provider, "{0}: {1:F}\n", "Today: ", 
                                      (DayOfWeek) DateTime.Now.DayOfWeek));
      Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n", 
                                      (Byte) 2, (Byte) 12, (Byte) 199));
      Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}\n", 
                                      (Byte) 2, (Byte) 12, (Byte) 199));
   }
}
// The example displays the following output:
//    Provider: InterceptProvider, Object: 10, Format String: N0
//    Provider: InterceptProvider, Object: 16.935, Format String: C2
//    Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
//    10: $16.94 on 1/31/2013
//    
//    Provider: InterceptProvider, Object: Today: , Format String: <null>
//    Provider: InterceptProvider, Object: Thursday, Format String: F
//    Today: : Thursday
//    
//    Provider: InterceptProvider, Object: 2, Format String: X
//    Provider: InterceptProvider, Object: 12, Format String: <null>
//    Provider: InterceptProvider, Object: 199, Format String: <null>
//    2, 12, 199
//    
//    Provider: InterceptProvider, Object: 2, Format String: R
//    Provider: InterceptProvider, Object: 12, Format String: R
//    Provider: InterceptProvider, Object: 199, Format String: R
//    II, XII, CXCIX
Imports System.Globalization

Public Class InterceptProvider : Implements IFormatProvider, ICustomFormatter
   Public Function GetFormat(formatType As Type) As Object _
         Implements IFormatProvider.GetFormat
      If formatType Is GetType(ICustomFormatter) Then
         Return Me
      Else
         Return Nothing
      End If
   End Function
   
   Public Function Format(fmt As String, obj As Object, provider As IFormatProvider) As String _
         Implements ICustomFormatter.Format

      Dim formatString As String = If(fmt IsNot Nothing, fmt, "<null>")
      Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
                        provider, If(obj IsNot Nothing, obj, "<null>"), formatString)

      If obj Is Nothing Then Return String.Empty
            
      ' If this is a byte and the "R" format string, format it with Roman numerals.
      If TypeOf(obj) Is Byte AndAlso formatString.ToUpper.Equals("R") Then
         Dim value As Byte = CByte(obj)
         Dim remainder As Integer
         Dim result As Integer
         Dim returnString As String = String.Empty

         ' Get the hundreds digit(s)
         result = Math.DivRem(value, 100, remainder)
         If result > 0 Then returnString = New String("C"c, result)
         value = CByte(remainder)
         ' Get the 50s digit
         result = Math.DivRem(value, 50, remainder)
         If result = 1 Then returnString += "L"
         value = CByte(remainder)
         ' Get the tens digit.
         result = Math.DivRem(value, 10, remainder)
         If result > 0 Then returnString += New String("X"c, result)
         value = CByte(remainder) 
         ' Get the fives digit.
         result = Math.DivRem(value, 5, remainder)
         If result > 0 Then returnString += "V"
         value = CByte(remainder)
         ' Add the ones digit.
         If remainder > 0 Then returnString += New String("I"c, remainder)
         
         ' Check whether we have too many X characters.
         Dim pos As Integer = returnString.IndexOf("XXXX")
         If pos >= 0 Then
            Dim xPos As Integer = returnString.IndexOf("L") 
            If xPos >= 0 And xPos = pos - 1 Then
               returnString = returnString.Replace("LXXXX", "XC")
            Else
               returnString = returnString.Replace("XXXX", "XL")   
            End If         
         End If
         ' Check whether we have too many I characters
         pos = returnString.IndexOf("IIII")
         If pos >= 0 Then
            If returnString.IndexOf("V") >= 0 Then
               returnString = returnString.Replace("VIIII", "IX")
            Else
               returnString = returnString.Replace("IIII", "IV")    
            End If
         End If
         Return returnString 
      End If   

      ' Use default for all other formatting.
      If obj Is GetType(IFormattable)
         Return CType(obj, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
      Else
         Return obj.ToString()
      End If
   End Function
End Class

Module Example
   Public Sub Main()
      Dim n As Integer = 10
      Dim value As Double = 16.935
      Dim day As DateTime = Date.Now
      Dim provider As New InterceptProvider()
      Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}", n, value, day))
      Console.WriteLine()
      Console.WriteLine(String.Format(provider, "{0}: {1:F}", "Today", 
                                      CType(Date.Now.DayOfWeek, DayOfWeek)))
      Console.WriteLine()
      Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n", 
                                      CByte(2), CByte(12), CByte(199)))
      Console.WriteLine()
      Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}", 
                                      CByte(2), CByte(12), CByte(199)))
   End Sub
End Module
' The example displays the following output:
'    Provider: InterceptProvider, Object: 10, Format String: N0
'    Provider: InterceptProvider, Object: 16.935, Format String: C2
'    Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
'    10: $16.94 on 1/31/2013
'    
'    Provider: InterceptProvider, Object: Today: , Format String: <null>
'    Provider: InterceptProvider, Object: Thursday, Format String: F
'    Today: : Thursday
'    
'    Provider: InterceptProvider, Object: 2, Format String: X
'    Provider: InterceptProvider, Object: 12, Format String: <null>
'    Provider: InterceptProvider, Object: 199, Format String: <null>
'    2, 12, 199
'    
'    Provider: InterceptProvider, Object: 2, Format String: R
'    Provider: InterceptProvider, Object: 12, Format String: R
'    Provider: InterceptProvider, Object: 199, Format String: R
'    II, XII, CXCIX

String.Format 問與答String.Format Q & A

為什麼建議字串內插補點透過呼叫String.Format方法?Why do you recommend string interpolation over calls to the String.Format method?

字串插補是:String interpolation is:

  • 更有彈性。More flexible. 它可以是任何字串中不需要使用支援複合格式方法的呼叫。It can be used in any string without requiring a call to a method that supports composite formatting. 否則,您必須呼叫Format方法或另一個方法,支援複合格式設定,例如Console.WriteLineStringBuilder.AppendFormatOtherwise, you have to call the Format method or another method that supports composite formatting, such as Console.WriteLine or StringBuilder.AppendFormat.

  • 更容易閱讀。More readable. 因為要插入至字串的運算式會出現在插入運算式中,而不是引數清單中,字串插值是最容易的程式碼和讀取。Because the expression to insert into a string appears in the interpolated expression rather than in a argument list, interpolated strings are far easier to code and to read. 因為其更高的可讀性,字串插值可以取代不只呼叫複合格式方法,但它們也可用在字串串連作業以產生更簡潔、 更清楚的程式碼。Because of their greater readability, interpolated strings can replace not only calls to composite format methods, but they can also be used in string concatenation operations to produce more concise, clearer code.

下列兩個程式碼範例的比較會說明字串插值的優勢,透過字串串連 」 和 「 複合格式化方法的呼叫。A comparison of the following two code examples illustrates the superiority of interpolated strings over string concatenation and calls to composite formatting methods. 在下列範例中的多個字串串連作業將會產生詳細資訊] 及 [硬讀取的程式碼。The use of multiple string concatenation operations in the following example produces verbose and hard-to-read code.

string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
string output = names[0] + ", " + names[1] + ", " + names[2] + ", " + 
                names[3] + ", " + names[4] + ", " + names[5] + ", " + 
                names[6];  

output += "\n";  
var date = DateTime.Now;
output += String.Format("It is {0:t} on {0:d}. The day of the week is {1}.", 
                        date, date.DayOfWeek);
Console.WriteLine(output);                           
// The example displays the following output:
//     Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
//     It is 10:29 AM on 1/8/2018. The day of the week is Monday.

Module Example
   Public Sub Main()
      Dim names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" }
      Dim output = names(0) + ", " + names(1) + ", " + names(2) + ", " + 
                   names(3) + ", " + names(4) + ", " + names(5) + ", " + 
                   names(6)  
    
      output += vbCrLf  
      Dim dat = DateTime.Now
      output += String.Format("It is {0:t} on {0:d}. The day of the week is {1}.", 
                              dat, dat.DayOfWeek)
      Console.WriteLine(output)                           
   End Sub
End Module
' The example displays the following output:
'     Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
'     It is 10:29 AM on 1/8/2018. The day of the week is Monday.


相較之下,使用插入字串,在下列範例會產生比字串串連陳述式和呼叫要清楚得多、 更簡潔的程式碼Format在上述範例中的方法。In contrast, the use of interpolated strings in the following example produce much clearer, more concise code than the string concatenation statement and the call to the Format method in the previous example.

string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
string output = $"{names[0]}, {names[1]}, {names[2]}, {names[3]}, {names[4]}, " + 
                $"{names[5]}, {names[6]}";  

var date = DateTime.Now;
output += $"\nIt is {date:t} on {date:d}. The day of the week is {date.DayOfWeek}.";
Console.WriteLine(output);                           
// The example displays the following output:
//     Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
//     It is 10:29 AM on 1/8/2018. The day of the week is Monday.

Module Example
   Public Sub Main()
      Dim names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" }
      Dim output = $"{names(0)}, {names(1)}, {names(2)}, {names(3)}, {names(4)}, " + 
                   $"{names(5)}, {names(6)}"  
    
      Dim dat = DateTime.Now
      output += $"{vbCrLf}It is {dat:t} on {dat:d}. The day of the week is {dat.DayOfWeek}." 
      Console.WriteLine(output)                           
   End Sub
End Module
' The example displays the following output:
'     Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
'     It is 10:29 AM on 1/8/2018. The day of the week is Monday.


哪裡可以找到預先定義的格式字串可以搭配格式項目清單?Where can I find a list of the predefined format strings that can be used with format items?

如何控制結果字串時,將格式項目的對齊方式?How do I control the alignment of the result strings that replace format items?

格式項目的一般語法如下:The general syntax of a format item is:

{index[,alignment][: formatString]}  

何處對齊是帶正負號的整數,定義欄位寬度。where alignment is a signed integer that defines the field width. 如果此值為負數,欄位中的文字會靠左對齊。If this value is negative, text in the field is left-aligned. 如果它是正數,則文字會靠右對齊。If it is positive, text is right-aligned.

如何控制小數分隔符號後的數字數目?How do I control the number of digits after the decimal separator?

所有標準數值格式字串除外 (這會只顯示整數) 的"D"、"G"、"R"和"X"允許的有效位數規範定義結果字串中的小數位數。All standard numeric format strings except "D" (which is used with integers only), "G", "R", and "X" allow a precision specifier that defines the number of decimal digits in the result string. 下列範例會使用標準數值格式字串來控制結果字串中的小數位數。The following example uses standard numeric format strings to control the number of decimal digits in the result string.

object[] values = { 1603, 1794.68235, 15436.14 };
string result;
foreach (var value in values) {
   result = String.Format("{0,12:C2}   {0,12:E3}   {0,12:F4}   {0,12:N3}  {1,12:P2}\n",
                          Convert.ToDouble(value), Convert.ToDouble(value) / 10000);
   Console.WriteLine(result);
}                           
// The example displays output like the following:
//       $1,603.00     1.603E+003      1603.0000      1,603.000       16.03 %
//    
//       $1,794.68     1.795E+003      1794.6824      1,794.682       17.95 %
//    
//      $15,436.14     1.544E+004     15436.1400     15,436.140      154.36 %
Module Example
   Public Sub Main()
      Dim values() As Object = { 1603, 1794.68235, 15436.14 }
      Dim result As String
      For Each value In values
         result = String.Format("{0,12:C2}   {0,12:E3}   {0,12:F4}   {0,12:N3}  {1,12:P2}",
                                value, CDbl(value) / 10000)
         Console.WriteLine(result) 
         Console.WriteLine()
      Next                             
   End Sub
End Module
' The example displays the following output:
'       $1,603.00     1.603E+003      1603.0000      1,603.000       16.03 %
'    
'       $1,794.68     1.795E+003      1794.6824      1,794.682       17.95 %
'    
'      $15,436.14     1.544E+004     15436.1400     15,436.140      154.36 %

如果您使用自訂數值格式字串,使用"0"的格式規範來控制在結果字串中,如下列範例所示的小數位數數目。If you're using a custom numeric format string, use the "0" format specifier to control the number of decimal digits in the result string, as the following example shows.

decimal value = 16309.5436m;
string result = String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}", 
                              value);
Console.WriteLine(result);
// The example displays the following output:
//        16309.54360    16,309.54    16309.544
Module Example
   Public Sub Main()
      Dim value As Decimal = 16309.5436d
      Dim result As String = String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}", 
                                           value)
      Console.WriteLine(result)
   End Sub
End Module
' The example displays the following output:
'    16309.54360    16,309.54    16309.544

如何控制整數位數數的字?How do I control the number of integral digits?

根據預設,格式化作業只會顯示非零的整數位數。By default, formatting operations only display non-zero integral digits. 如果您要格式化的整數,您可以使用精確度規範"D"和"X"標準格式字串來控制的位數。If you are formatting integers, you can use a precision specifier with the "D" and "X" standard format strings to control the number of digits.

int value = 1326;
string result = String.Format("{0,10:D6} {0,10:X8}", value);
Console.WriteLine(result);
// The example displays the following output:
//     001326   0000052E
Module Example
   Public Sub Main()
      Dim value As Integer = 1326
      Dim result As String = String.Format("{0,10:D6} {0,10:X8}", value)
      Console.WriteLine(result)
   End Sub
End Module
' The example displays the following output:
'       001326   0000052E

您可以填補整數或浮點數,加上前置零來使用 「 0 」 產生的結果字串會以指定的數字的整數位數自訂數值格式規範,如下列範例所示。You can pad an integer or floating-point number with leading zeros to produce a result string with a specified number of integral digits by using the "0" custom numeric format specifier, as the following example shows.

int value = 16342;
string result = String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}", 
                              value);
Console.WriteLine(result);
// The example displays the following output:
//           00016342       00016342.000    0,000,016,342.0
Module Example
   Public Sub Main()
      Dim value As Integer = 16342
      Dim result As String = String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}", 
                                           value)
      Console.WriteLine(result)
   End Sub
End Module
' The example displays the following output:
'           00016342       00016342.000    0,000,016,342.0

是否可以在 [格式] 清單中包含多少個項目?How many items can I include in the format list?

沒有任何實際的限制。There is no practical limit. 第二個參數Format(IFormatProvider, String, Object[])方法會標記為ParamArrayAttribute屬性,可讓您包含分隔的清單或物件陣列做為您的格式清單。The second parameter of the Format(IFormatProvider, String, Object[]) method is tagged with the ParamArrayAttribute attribute, which allows you to include either a delimited list or an object array as your format list.

我該如何包含常值大括號 ("{"和"}") 結果字串中?How do I include literal braces ("{" and "}") in the result string?

比方說,如何執行您避免下列方法呼叫擲回FormatException例外狀況?For example, how do you prevent the following method call from throwing a FormatException exception?

result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
                       nOpen, nClose);
result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
                       nOpen, nClose)

單一的左或右大括號一律會解譯為開頭或結尾的格式項目中。A single opening or closing brace is always interpreted as the beginning or end of a format item. 若要解譯為常值,則必須逸出。To be interpreted literally, it must be escaped. 您新增另一個大括號逸出大括號 ("{{"和"}} 」 而不是"{"和"}"),如下列方法呼叫:You escape a brace by adding another brace ("{{" and "}}" instead of "{" and "}"), as in the following method call:

string result;
int nOpen = 1;
int nClose = 2;
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
                       nOpen, nClose);
Console.WriteLine(result);
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
                       nOpen, nClose)

不過,即使逸出大括號會輕易地譯。However, even escaped braces are easily misinterpreted. 我們建議您在 [格式] 清單中包含大括號,並使用將其插入在結果字串中,如下列範例所示的格式項目。We recommend that you include braces in the format list and use format items to insert them in the result string, as the following example shows.

string result;
int nOpen = 1;
int nClose = 2;
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
                       nOpen, "{", nClose, "}");
Console.WriteLine(result);
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
                       nOpen, "{", nClose, "}")

為什麼我呼叫 String.Format 方法擲回 FormatException?Why does my call to the String.Format method throw a FormatException?

最常見的例外狀況的原因是格式項目的索引未對應至 [格式] 清單中的物件。The most common cause of the exception is that the index of a format item doesn't correspond to an object in the format list. 通常這表示您已 misnumbered 格式項目的索引,或是您忘記在 [格式] 清單中包含的物件。Usually this indicates that you've misnumbered the indexes of format items or you've forgotten to include an object in the format list. 嘗試將包含未逸出的左或右括弧字元也會擲回FormatExceptionAttempting to include an unescaped left or right brace character also throws a FormatException. 有時候,例外狀況是打錯字; 的結果例如,典型的錯誤是打錯"["(左括號) 而不是"{"(左括號)。Occasionally, the exception is the result of a typo; for example, a typical mistake is to mistype "[" (the left bracket) instead of "{" (the left brace).

如果 Format(System.IFormatProvider,System.String,System.Object[]) 方法支援參數陣列,為何沒有我的程式碼時擲回例外狀況使用陣列嗎?If the Format(System.IFormatProvider,System.String,System.Object[]) method supports parameter arrays, why does my code throw an exception when I use an array?

例如,下列程式碼會擲回FormatException例外狀況:For example, the following code throws a FormatException exception:

Random rnd = new Random();
int[]  numbers = new int[4];
int total = 0;
for (int ctr = 0; ctr <= 2; ctr++) {
   int number = rnd.Next(1001);
   numbers[ctr] = number;
   total += number;
}   
numbers[3] = total;
Console.WriteLine("{0} + {1} + {2} = {3}", numbers);   
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim numbers(3) As Integer
      Dim total As Integer = 0
      For ctr = 0 To 2
         Dim number As Integer = rnd.Next(1001)
         numbers(ctr) = number
         total += number
      Next
      numbers(3) = total
      Console.WriteLine("{0} + {1} + {2} = {3}", numbers)   
   End Sub
End Module

這是編譯器多載解析的問題。This is a problem of compiler overload resolution. 因為編譯器無法將整數的陣列轉換成物件陣列,它會將整數陣列視為單一引數,因此它會呼叫Format(String, Object)方法。Because the compiler cannot convert an array of integers to an object array, it treats the integer array as a single argument, so it calls the Format(String, Object) method. 因為有四個格式項目,但單一項目格式 清單中的,則會擲回例外狀況。The exception is thrown because there are four format items but only a single item in the format list.

由於 Visual Basic 和 C# 都不可以轉換成物件陣列的整數陣列,您必須自行執行轉換,然後再呼叫Format(String, Object[])方法。Because neither Visual Basic nor C# can convert an integer array to an object array, you have to perform the conversion yourself before calling the Format(String, Object[]) method. 下列範例提供一個實作。The following example provides one implementation.

Random rnd = new Random();
int[]  numbers = new int[4];
int total = 0;
for (int ctr = 0; ctr <= 2; ctr++) {
   int number = rnd.Next(1001);
   numbers[ctr] = number;
   total += number;
}   
numbers[3] = total;
object[] values = new object[numbers.Length];
numbers.CopyTo(values, 0);
Console.WriteLine("{0} + {1} + {2} = {3}", values);   
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim numbers(3) As Integer
      Dim total As Integer = 0
      For ctr = 0 To 2
         Dim number As Integer = rnd.Next(1001)
         numbers(ctr) = number
         total += number
      Next
      numbers(3) = total
      Dim values(numbers.Length - 1) As Object
      numbers.CopyTo(values, 0) 
      Console.WriteLine("{0} + {1} + {2} = {3}", values)   
   End Sub
End Module

Format(String, Object) Format(String, Object) Format(String, Object) Format(String, Object)

以指定物件的字串表示,取代字串中的一或多個格式項目。Replaces one or more format items in a string with the string representation of a specified object.

public:
 static System::String ^ Format(System::String ^ format, System::Object ^ arg0);
public static string Format (string format, object arg0);
static member Format : string * obj -> string
Public Shared Function Format (format As String, arg0 As Object) As String

參數

arg0
Object Object Object Object

要格式化的物件。The object to format.

傳回

format 的複本,其中的所有格式項目已由 arg0 的字串表示取代。A copy of format in which any format items are replaced by the string representation of arg0.

例外狀況

format 中的格式項目無效。The format item in format is invalid.

-或--or- 格式項目的索引不是零。The index of a format item is not zero.

備註

重要

請不要呼叫 String.Format 方法或使用複合格式字串,您可以使用「內插字串」 (如果您的語言支援它們的話)。Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. 內插字串是包含「插入運算式」 的字串。An interpolated string is a string that contains interpolated expressions. 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. 如需詳細資訊,請參閱內插字串 (C# 參考)內插字串 (Visual Basic 參考)For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

這個方法會使用複合格式功能將運算式的值轉換為其字串表示,並在字串中內嵌該表示法。This method uses the composite formatting feature to convert the value of an expression to its string representation and to embed that representation in a string.

不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. 相反地,您可以使用包含一或多個格式項目的複合格式字串來呼叫該方法。Instead, you can call the method with a composite format string that includes one or more format items. 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。You assign each format item a numeric index; the first index starts at 0. 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。In addition to the initial string, your method call should have as many additional arguments as it has index values. 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。Your language compiler will then resolve your method call to a particular overload of the String.Format method.

如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門要呼叫哪個方法?For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.

範例:格式化的單一引數Example: Formatting a single argument

下列範例會使用Format(String, Object)內嵌在字串當中的個人的年齡的方法。The following example uses the Format(String, Object) method to embed an individual's age in the middle of a string.

using namespace System;

void main()
{
   DateTime birthdate = DateTime(1993, 7, 28);
   array<DateTime>^ dates = gcnew array<DateTime> { DateTime(1993, 8, 16), 
                                                    DateTime(1994, 7, 28), 
                                                    DateTime(2000, 10, 16), 
                                                    DateTime(2003, 7, 27), 
                                                    DateTime(2007, 5, 27) };

   for each (DateTime dateValue in dates)
   {
      TimeSpan interval = dateValue - birthdate;
      // Get the approximate number of years, without accounting for leap years.
      int years = ((int)interval.TotalDays) / 365;
      // See if adding the number of years exceeds dateValue.
      String^ output;
      if (birthdate.AddYears(years) <= dateValue) {
         output = String::Format("You are now {0} years old.", years);
         Console::WriteLine(output);
      }   
      else {
         output = String::Format("You are now {0} years old.", years - 1);
         Console::WriteLine(output);
      }      
   }
}
// The example displays the following output:
//       You are now 0 years old.
//       You are now 1 years old.
//       You are now 7 years old.
//       You are now 9 years old.
//       You are now 13 years old.
DateTime birthdate = new DateTime(1993, 7, 28);
DateTime[] dates = { new DateTime(1993, 8, 16), 
                     new DateTime(1994, 7, 28), 
                     new DateTime(2000, 10, 16), 
                     new DateTime(2003, 7, 27), 
                     new DateTime(2007, 5, 27) };

foreach (DateTime dateValue in dates)
{
   TimeSpan interval = dateValue - birthdate;
   // Get the approximate number of years, without accounting for leap years.
   int years = ((int) interval.TotalDays) / 365;
   // See if adding the number of years exceeds dateValue.
   string output;
   if (birthdate.AddYears(years) <= dateValue) {
      output = String.Format("You are now {0} years old.", years);
      Console.WriteLine(output);
   }   
   else {
      output = String.Format("You are now {0} years old.", years - 1);
      Console.WriteLine(output);
   }      
}
// The example displays the following output:
//       You are now 0 years old.
//       You are now 1 years old.
//       You are now 7 years old.
//       You are now 9 years old.
//       You are now 13 years old.
Module Example
   Public Sub Main()
      Dim birthdate As Date = #7/28/1993#
      Dim dates() As Date = { #9/16/1993#, #7/28/1994#, #10/16/2000#, _
                              #7/27/2003#, #5/27/2007# }
      For Each dateValue As Date In dates
         Dim interval As TimeSpan = dateValue - birthdate
         ' Get the approximate number of years, without accounting for leap years.
         Dim years As Integer = CInt(interval.TotalDays) \ 365
         ' See if adding the number of years exceeds dateValue.
         Dim output As String
         If birthdate.AddYears(years) <= dateValue Then
            output = String.Format("You are now {0} years old.", years)
            Console.WriteLine(output)
         Else
            output = String.Format("You are now {0} years old.", years - 1)
            Console.WriteLine(output)   
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'       You are now 0 years old.
'       You are now 1 years old.
'       You are now 7 years old.
'       You are now 9 years old.
'       You are now 13 years old.
另請參閱

Format(String, Object[]) Format(String, Object[]) Format(String, Object[]) Format(String, Object[])

以指定陣列中對應物件的字串表示,取代指定之字串中的格式項目。Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.

public:
 static System::String ^ Format(System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (string format, params object[] args);
static member Format : string * obj[] -> string
Public Shared Function Format (format As String, ParamArray args As Object()) As String

參數

args
Object[]

物件陣列,包含零或多個要格式化的物件。An object array that contains zero or more objects to format.

傳回

format 的複本,其中的格式項目已由 args 中對應物件的字串表示取代。A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.

例外狀況

formatargsnullformat or args is null.

format 無效。format is invalid.

-或--or- 格式項目的索引小於零,或大於等於 args 陣列的長度。The index of a format item is less than zero, or greater than or equal to the length of the args array.

備註

重要

請不要呼叫 String.Format 方法或使用複合格式字串,您可以使用「內插字串」 (如果您的語言支援它們的話)。Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. 內插字串是包含「插入運算式」 的字串。An interpolated string is a string that contains interpolated expressions. 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. 如需詳細資訊,請參閱內插字串 (C# 參考)內插字串 (Visual Basic 參考)For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

這個方法會使用複合格式功能四個或多個運算式的值轉換成其字串表示法,並內嵌在字串中的那些表示法。This method uses the composite formatting feature to convert the value of four or more expressions to their string representations and to embed those representations in a string. 由於args參數會標示System.ParamArrayAttribute屬性,您可以將物件傳遞至方法做為個別引數,或為Object陣列。Since the args parameter is marked with the System.ParamArrayAttribute attribute, you can pass the objects to the method as individual arguments or as an Object array.

不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. 相反地,您可以使用包含一或多個格式項目的複合格式字串來呼叫該方法。Instead, you can call the method with a composite format string that includes one or more format items. 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。You assign each format item a numeric index; the first index starts at 0. 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。In addition to the initial string, your method call should have as many additional arguments as it has index values. 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。Your language compiler will then resolve your method call to a particular overload of the String.Format method.

如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門要呼叫哪個方法?For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.

範例:設定格式化的三個以上的引數Example: Formatting more than three arguments

這個範例會建立包含在特定日期的高低溫度資料的字串。This example creates a string that contains data on the high and low temperature on a particular date. 複合格式字串有五個格式項目,在 C# 範例和六個 in Visual Basic 範例。The composite format string has five format items in the C# example and six in the Visual Basic example. 兩個格式項目定義及其對應值的字串表示法,寬度,而且第一個格式項目,也包含的標準日期和時間格式字串。Two of the format items define the width of their corresponding value's string representation, and the first format item also includes a standard date and time format string.

using namespace System;

void main()
{
   DateTime date1 = DateTime(2009, 7, 1);
   TimeSpan hiTime = TimeSpan(14, 17, 32);
   Decimal hiTemp = (Decimal) 62.1; 
   TimeSpan loTime = TimeSpan(3, 16, 10);
   Decimal loTemp = (Decimal)54.8; 

   String^ result1 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                                    date1, hiTime, hiTemp, loTime, loTemp);
   Console::WriteLine(result1);
   Console::WriteLine();
           
   String^ result2 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                                    gcnew array<Object^> { date1, hiTime, hiTemp, loTime, loTemp });
   Console::WriteLine(result2);
}
// The example displays the following output:
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
DateTime date1 = new DateTime(2009, 7, 1);
TimeSpan hiTime = new TimeSpan(14, 17, 32);
decimal hiTemp = 62.1m; 
TimeSpan loTime = new TimeSpan(3, 16, 10);
decimal loTemp = 54.8m; 

string result1 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                               date1, hiTime, hiTemp, loTime, loTemp);
Console.WriteLine(result1);
Console.WriteLine();
     
string result2 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                               new object[] { date1, hiTime, hiTemp, loTime, loTemp });
Console.WriteLine(result2);
// The example displays output like the following:
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
Module Example
   Public Sub Main()
      Dim date1 As Date = #7/1/2009#
      Dim hiTime As New TimeSpan(14, 17, 32)
      Dim hiTemp As Decimal = 62.1d 
      Dim loTime As New TimeSpan(3, 16, 10)
      Dim loTemp As Decimal = 54.8d 

      Dim result1 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
                                           date1, hiTime, hiTemp, loTime, loTemp, vbCrLf)
      Console.WriteLine(result1)
      Console.WriteLine()
           
      Dim result2 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
                                            New Object() { date1, hiTime, hiTemp, loTime, loTemp, vbCrLf })
      Console.WriteLine(result2)                                            
   End Sub
End Module
' The example displays the following output:
'       Temperature on 7/1/2009:
'          14:17:32: 62.1 degrees (hi)
'          03:16:10: 54.8 degrees (lo)
'
'       Temperature on 7/1/2009:
'          14:17:32: 62.1 degrees (hi)
'          03:16:10: 54.8 degrees (lo)

您也可以傳遞要格式化為陣列,而不是做為引數清單的物件。You can also pass the objects to be formatted as an array rather than as an argument list.

using namespace System;

ref class CityInfo
{
public:
   CityInfo(String^ name, int population, Decimal area, int year)
   {
      this->Name = name;
      this->Population = population;
      this->Area = area;
      this->Year = year;
   }
   
   String^ Name; 
   int Population;
   Decimal Area;
   int Year;
};

ref class Example
{
public:
   static void ShowPopulationData(CityInfo^ city)
   {
      array<Object^>^ args = gcnew array<Object^> { city->Name, city->Year, city->Population, city->Area };
      String^ result = String::Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", 
                                    args);
      Console::WriteLine(result); 
   }
};

void main()
{
   CityInfo^ nyc2010 = gcnew CityInfo("New York", 8175133, (Decimal) 302.64, 2010);
   Example::ShowPopulationData(nyc2010);
   CityInfo^ sea2010 = gcnew CityInfo("Seattle", 608660, (Decimal) 83.94, 2010);      
   Example::ShowPopulationData(sea2010); 
}
// The example displays the following output:
//       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
//       Seattle in 2010: Population 608,660, Area 83.9 sq. feet
using System;

public class CityInfo
{
   public CityInfo(String name, int population, Decimal area, int year)
   {
      this.Name = name;
      this.Population = population;
      this.Area = area;
      this.Year = year;
   }
   
   public readonly String Name; 
   public readonly int Population;
   public readonly Decimal Area;
   public readonly int Year;
}

public class Example
{
   public static void Main()
   {
      CityInfo nyc2010 = new CityInfo("New York", 8175133, 302.64m, 2010);
      ShowPopulationData(nyc2010);
      CityInfo sea2010 = new CityInfo("Seattle", 608660, 83.94m, 2010);      
      ShowPopulationData(sea2010); 
   }

   private static void ShowPopulationData(CityInfo city)
   {
      object[] args = { city.Name, city.Year, city.Population, city.Area };
      String result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", 
                                    args);
      Console.WriteLine(result); 
   }
}
// The example displays the following output:
//       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
//       Seattle in 2010: Population 608,660, Area 83.9 sq. feet
Public Class CityInfo
   Public Sub New(name As String, population As Integer, area As Decimal, year As Integer)
      Me.Name = name
      Me.Population = population
      Me.Area = area
      Me.Year = year
   End Sub
   
   Public ReadOnly Name As String
   Public ReadOnly Population As Integer
   Public ReadOnly Area As Decimal
   Public ReadOnly Year As Integer
End Class

Module Example
   Public Sub Main()
      Dim nyc2010 As New CityInfo("New York", 8175133, 302.64d, 2010)
      ShowPopulationData(nyc2010)
      Dim sea2010 As New CityInfo("Seattle", 608660, 83.94d, 2010)      
      ShowPopulationData(sea2010) 
   End Sub
   
   Private Sub ShowPopulationData(city As CityInfo)
      Dim args() As Object = { city.Name, city.Year, city.Population, city.Area }
      Dim result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", args)
      Console.WriteLine(result) 
   End Sub
End Module
' The example displays the following output:
'       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
'       Seattle in 2010: Population 608,660, Area 83.9 sq. feet   
另請參閱

Format(IFormatProvider, String, Object) Format(IFormatProvider, String, Object) Format(IFormatProvider, String, Object) Format(IFormatProvider, String, Object)

以對應物件的字串表示,取代指定之字串中的一或多個格式項目。Replaces the format item or items in a specified string with the string representation of the corresponding object. 參數提供特定文化特性格式資訊。A parameter supplies culture-specific formatting information.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0);
public static string Format (IFormatProvider provider, string format, object arg0);
static member Format : IFormatProvider * string * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object) As String

參數

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

物件,提供特定文化特性格式資訊。An object that supplies culture-specific formatting information.

arg0
Object Object Object Object

要格式化的物件。The object to format.

傳回

format 的複本,其中的一或多個格式項目已由 arg0 的字串表示取代。A copy of format in which the format item or items have been replaced by the string representation of arg0.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引不是零。The index of a format item is not zero.

備註

重要

請不要呼叫 String.Format 方法或使用複合格式字串,您可以使用「內插字串」 (如果您的語言支援它們的話)。Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. 內插字串是包含「插入運算式」 的字串。An interpolated string is a string that contains interpolated expressions. 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. 如需詳細資訊,請參閱內插字串 (C# 參考)內插字串 (Visual Basic 參考)For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

這個方法會使用複合格式功能將運算式的值轉換為其字串表示,並在字串中內嵌該表示法。This method uses the composite formatting feature to convert the value of an expression to its string representation and to embed that representation in a string. 在執行轉換,該方法會使用區分文化特性格式,或自訂格式器。In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. 方法會將轉換arg0為其字串表示,藉由呼叫其ToString(IFormatProvider) 方法或,如果物件的對應格式項目會包含格式字串,藉由呼叫其ToString (String,IFormatProvider) 方法。The method converts arg0 to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. 如果這些方法不存在,則會呼叫物件的無參數ToString方法。If these methods don't exist, it calls the object's parameterless ToString method.

不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. 相反地,您可以使用提供區分文化特性或自訂格式的物件和包含一或多個格式項目的複合格式字串來呼叫該方法。Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。You assign each format item a numeric index; the first index starts at 0. 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。In addition to the initial string, your method call should have as many additional arguments as it has index values. 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。Your language compiler will then resolve your method call to a particular overload of the String.Format method.

如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門要呼叫哪個方法?For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.

Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[])

以指定陣列中對應物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representations of corresponding objects in a specified array. 參數提供特定文化特性格式資訊。A parameter supplies culture-specific formatting information.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (IFormatProvider provider, string format, params object[] args);
static member Format : IFormatProvider * string * obj[] -> string
Public Shared Function Format (provider As IFormatProvider, format As String, ParamArray args As Object()) As String

參數

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

物件,提供特定文化特性格式資訊。An object that supplies culture-specific formatting information.

args
Object[]

物件陣列,包含零或多個要格式化的物件。An object array that contains zero or more objects to format.

傳回

format 的複本,其中的格式項目已由 args 中對應物件的字串表示取代。A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.

例外狀況

formatargsnullformat or args is null.

format 無效。format is invalid.

-或--or- 格式項目的索引小於零,或大於等於 args 陣列的長度。The index of a format item is less than zero, or greater than or equal to the length of the args array.

備註

重要

請不要呼叫 String.Format 方法或使用複合格式字串,您可以使用「內插字串」 (如果您的語言支援它們的話)。Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. 內插字串是包含「插入運算式」 的字串。An interpolated string is a string that contains interpolated expressions. 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. 如需詳細資訊,請參閱內插字串 (C# 參考)內插字串 (Visual Basic 參考)For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

這個方法會使用複合格式功能將四個或多個運算式轉換成其字串表示法,並內嵌在字串中的那些表示法。This method uses the composite formatting feature to convert four or more expressions to their string representations and to embed those representations in a string. 在執行轉換,該方法會使用區分文化特性格式,或自訂格式器。In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. 方法會將每個Object引數為其字串表示,藉由呼叫其ToString(IFormatProvider) 方法或,如果物件的對應格式項目會包含格式字串,藉由呼叫其ToString(String,IFormatProvider) 方法。The method converts each Object argument to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. 如果這些方法不存在,則會呼叫物件的無參數ToString方法。If these methods don't exist, it calls the object's parameterless ToString method.

不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. 相反地,您可以使用提供區分文化特性或自訂格式的物件和包含一或多個格式項目的複合格式字串來呼叫該方法。Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。You assign each format item a numeric index; the first index starts at 0. 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。In addition to the initial string, your method call should have as many additional arguments as it has index values. 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。Your language compiler will then resolve your method call to a particular overload of the String.Format method.

如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門要呼叫哪個方法?For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.

範例:區分文化特性格式Example: Culture-sensitive formatting

這個範例會使用Format(IFormatProvider, String, Object[])方法,以使用數個不同的文化特性顯示一些日期和時間值和數字值的字串表示。This example uses the Format(IFormatProvider, String, Object[]) method to display the string representation of some date and time values and numeric values by using several different cultures.

string[] cultureNames = { "en-US", "fr-FR", "de-DE", "es-ES" };

DateTime dateToDisplay = new DateTime(2009, 9, 1, 18, 32, 0);
double value = 9164.32;

Console.WriteLine("Culture     Date                                Value\n");
foreach (string cultureName in cultureNames)
{
   System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
   string output = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", 
                                 culture.Name, dateToDisplay, value);
   Console.WriteLine(output);
}    
// The example displays the following output:
//    Culture     Date                                Value
//    
//    en-US       Tuesday, September 01, 2009         9,164.32
//    fr-FR       mardi 1 septembre 2009              9 164,32
//    de-DE       Dienstag, 1. September 2009         9.164,32
//    es-ES       martes, 01 de septiembre de 2009    9.164,32
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "fr-FR", "de-DE", "es-ES" }
      
      Dim dateToDisplay As Date = #9/1/2009 6:32PM#
      Dim value As Double = 9164.32

      Console.WriteLine("Culture     Date                                Value")
      Console.WriteLine()      
      For Each cultureName As String In cultureNames
         Dim culture As New CultureInfo(cultureName)
         Dim output As String = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", _
                                              culture.Name, dateToDisplay, value)
         Console.WriteLine(output)
      Next    
   End Sub
End Module
' The example displays the following output:
'       Culture     Date                                Value
'       
'       en-US       Tuesday, September 01, 2009         9,164.32
'       fr-FR       mardi 1 septembre 2009              9 164,32
'       de-DE       Dienstag, 1. September 2009         9.164,32
'       es-ES       martes, 01 de septiembre de 2009    9.164,32
另請參閱

Format(String, Object, Object) Format(String, Object, Object) Format(String, Object, Object) Format(String, Object, Object)

以兩個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of two specified objects.

public:
 static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (string format, object arg0, object arg1);
static member Format : string * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object) As String

參數

arg0
Object Object Object Object

要格式化的第一個物件。The first object to format.

arg1
Object Object Object Object

要格式化的第二個物件。The second object to format.

傳回

format 的複本,其中的格式項目已由 arg0arg1 的字串表示取代。A copy of format in which format items are replaced by the string representations of arg0 and arg1.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引不是零或一。The index of a format item is not zero or one.

備註

重要

請不要呼叫 String.Format 方法或使用複合格式字串,您可以使用「內插字串」 (如果您的語言支援它們的話)。Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. 內插字串是包含「插入運算式」 的字串。An interpolated string is a string that contains interpolated expressions. 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. 如需詳細資訊,請參閱內插字串 (C# 參考)內插字串 (Visual Basic 參考)For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

這個方法會使用複合格式功能將兩個運算式的值轉換成其字串表示法,並內嵌在字串中的那些表示法。This method uses the composite formatting feature to convert the value of two expressions to their string representations and to embed those representations in a string.

不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. 相反地,您可以使用包含一或多個格式項目的複合格式字串來呼叫該方法。Instead, you can call the method with a composite format string that includes one or more format items. 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。You assign each format item a numeric index; the first index starts at 0. 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。In addition to the initial string, your method call should have as many additional arguments as it has index values. 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。Your language compiler will then resolve your method call to a particular overload of the String.Format method.

如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門要呼叫哪個方法?For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.

範例:格式化的兩個引數Example: Formatting two arguments

這個範例會使用Format(String, Object, Object)方法,以顯示儲存在一般時間和溫度資料Dictionary<TKey,TValue>物件。This example uses the Format(String, Object, Object) method to display time and temperature data stored in a generic Dictionary<TKey,TValue> object. 請注意,格式字串會有三個格式項目,雖然只有兩個要格式化的物件。Note that the format string has three format items, although there are only two objects to format. 這是因為在清單中 (日期和時間值) 的第一個物件由兩個格式項目:第一個格式項目會顯示第二個情況下,就會顯示日期。This is because the first object in the list (a date and time value) is used by two format items: The first format item displays the time, and the second displays the date.

using namespace System;
using namespace System::Collections::Generic;

void main()
{
   Dictionary<DateTime, Double>^ temperatureInfo = gcnew Dictionary<DateTime, Double>(); 
   temperatureInfo->Add(DateTime(2010, 6, 1, 14, 0, 0), 87.46);
   temperatureInfo->Add(DateTime(2010, 12, 1, 10, 0, 0), 36.81);
      
   Console::WriteLine("Temperature Information:\n");
   String^ output;   
   for each (KeyValuePair<DateTime, Double>^ item in temperatureInfo)
   {
      output = String::Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}�F", 
                              item->Key, item->Value);
      Console::WriteLine(output);
   }
}
// The example displays the following output:
//       Temperature Information:
//       
//       Temperature at  2:00 PM on  6/1/2010:  87.5�F
//       Temperature at 10:00 AM on 12/1/2010:  36.8�F
Dictionary<DateTime, Double> temperatureInfo = new Dictionary<DateTime, Double>(); 
temperatureInfo.Add(new DateTime(2010, 6, 1, 14, 0, 0), 87.46);
temperatureInfo.Add(new DateTime(2010, 12, 1, 10, 0, 0), 36.81);

Console.WriteLine("Temperature Information:\n");
string output;   
foreach (var item in temperatureInfo)
{
   output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", 
                          item.Key, item.Value);
   Console.WriteLine(output);
}
// The example displays output like the following:
//       Temperature Information:
//       
//       Temperature at  2:00 PM on  6/1/2010:  87.5°F
//       Temperature at 10:00 AM on 12/1/2010:  36.8°F
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim temperatureInfo As New Dictionary(Of Date, Double) 
      temperatureInfo.Add(#6/1/2010 2:00PM#, 87.46)
      temperatureInfo.Add(#12/1/2010 10:00AM#, 36.81)
      
      Console.WriteLine("Temperature Information:")
      Console.WriteLine()
      Dim output As String   
      For Each item In temperatureInfo
         output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", _
                                item.Key, item.Value)
         Console.WriteLine(output)
      Next
   End Sub
End Module
' The example displays the following output:
'       Temperature Information:
'       
'       Temperature at  2:00 PM on  6/1/2010:  87.5°F
'       Temperature at 10:00 AM on 12/1/2010:  36.8°F
另請參閱

Format(IFormatProvider, String, Object, Object) Format(IFormatProvider, String, Object, Object) Format(IFormatProvider, String, Object, Object) Format(IFormatProvider, String, Object, Object)

以兩個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of two specified objects. 參數提供特定文化特性格式資訊。A parameter supplies culture-specific formatting information.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1);
static member Format : IFormatProvider * string * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object) As String

參數

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

物件,提供特定文化特性格式資訊。An object that supplies culture-specific formatting information.

arg0
Object Object Object Object

要格式化的第一個物件。The first object to format.

arg1
Object Object Object Object

要格式化的第二個物件。The second object to format.

傳回

format 的複本,其中的格式項目已由 arg0arg1 的字串表示取代。A copy of format in which format items are replaced by the string representations of arg0 and arg1.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引不是零或一。The index of a format item is not zero or one.

備註

重要

請不要呼叫 String.Format 方法或使用複合格式字串,您可以使用「內插字串」 (如果您的語言支援它們的話)。Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. 內插字串是包含「插入運算式」 的字串。An interpolated string is a string that contains interpolated expressions. 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. 如需詳細資訊,請參閱內插字串 (C# 參考)內插字串 (Visual Basic 參考)For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

這個方法會使用複合格式功能將兩個運算式轉換成其字串表示法,並內嵌在字串中的那些表示法。This method uses the composite formatting feature to convert two expressions to their string representations and to embed those representations in a string. 在執行轉換,該方法會使用區分文化特性格式,或自訂格式器。In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. 方法會將每個Object引數為其字串表示,藉由呼叫其ToString(IFormatProvider) 方法或,如果物件的對應格式項目會包含格式字串,藉由呼叫其ToString(String,IFormatProvider) 方法。The method converts each Object argument to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. 如果這些方法不存在,則會呼叫物件的無參數ToString方法。If these methods don't exist, it calls the object's parameterless ToString method.

不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. 相反地,您可以使用提供區分文化特性或自訂格式的物件和包含一或多個格式項目的複合格式字串來呼叫該方法。Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。You assign each format item a numeric index; the first index starts at 0. 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。In addition to the initial string, your method call should have as many additional arguments as it has index values. 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。Your language compiler will then resolve your method call to a particular overload of the String.Format method.

如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門要呼叫哪個方法?For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.

Format(String, Object, Object, Object) Format(String, Object, Object, Object) Format(String, Object, Object, Object) Format(String, Object, Object, Object)

以三個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of three specified objects.

public:
 static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (string format, object arg0, object arg1, object arg2);
static member Format : string * obj * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String

參數

arg0
Object Object Object Object

要格式化的第一個物件。The first object to format.

arg1
Object Object Object Object

要格式化的第二個物件。The second object to format.

arg2
Object Object Object Object

要格式化的第三個物件。The third object to format.

傳回

format 的複本,其中的格式項目已由 arg0arg1arg2 的字串表示取代。A copy of format in which the format items have been replaced by the string representations of arg0, arg1, and arg2.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引小於零或大於二。The index of a format item is less than zero, or greater than two.

備註

重要

請不要呼叫 String.Format 方法或使用複合格式字串,您可以使用「內插字串」 (如果您的語言支援它們的話)。Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. 內插字串是包含「插入運算式」 的字串。An interpolated string is a string that contains interpolated expressions. 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. 如需詳細資訊,請參閱內插字串 (C# 參考)內插字串 (Visual Basic 參考)For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

這個方法會使用複合格式功能三個運算式的值轉換成其字串表示法,並內嵌在字串中的那些表示法。This method uses the composite formatting feature to convert the value of three expressions to their string representations and to embed those representations in a string.

不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. 相反地,您可以使用包含一或多個格式項目的複合格式字串來呼叫該方法。Instead, you can call the method with a composite format string that includes one or more format items. 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。You assign each format item a numeric index; the first index starts at 0. 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。In addition to the initial string, your method call should have as many additional arguments as it has index values. 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。Your language compiler will then resolve your method call to a particular overload of the String.Format method.

如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門要呼叫哪個方法?For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.

範例:格式的三個引數Example: Formatting three arguments

這個範例會使用Format(String, Object, Object, Object)方法來建立說明的布林值結果字串And與兩個整數值的作業。This example uses the Format(String, Object, Object, Object) method to create a string that illustrates the result of a Boolean And operation with two integer values. 請注意,格式字串包含六個格式項目,但方法具有三個項目在其參數清單中,因為每個項目兩種不同方式格式化。Note that the format string includes six format items, but the method has only three items in its parameter list, because each item is formatted in two different ways.

using namespace System;

void main()
{
   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);
   Console::WriteLine(result);
}
// The example displays the following output:
//                16932 (00004224)
//       And      15421 (00003C3D)
//         =         36 (00000024)
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);
Console.WriteLine(result);
// The example displays the following output:
//                16932 (00004224)
//       And      15421 (00003C3D)
//         =         36 (00000024)
Public Module Example
   Public Sub Main()
      Dim formatString As String = "    {0,10} ({0,8:X8})" + vbCrLf +  _
                                   "And {1,10} ({1,8:X8})" + vbCrLf + _
                                   "  = {2,10} ({2,8:X8})"
      Dim value1 As Integer = 16932
      Dim value2 As Integer = 15421
      Dim result As String = String.Format(formatString, _
                                           value1, value2, value1 And value2)
      Console.WriteLine(result)                          
   End Sub
End Module
' The example displays the following output:
'                16932 (00004224)
'       And      15421 (00003C3D)
'         =         36 (00000024)
另請參閱

Format(IFormatProvider, String, Object, Object, Object) Format(IFormatProvider, String, Object, Object, Object) Format(IFormatProvider, String, Object, Object, Object) Format(IFormatProvider, String, Object, Object, Object)

以三個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of three specified objects. 參數提供特定文化特性格式資訊。An parameter supplies culture-specific formatting information.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1, object arg2);
static member Format : IFormatProvider * string * obj * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String

參數

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

物件,提供特定文化特性格式資訊。An object that supplies culture-specific formatting information.

arg0
Object Object Object Object

要格式化的第一個物件。The first object to format.

arg1
Object Object Object Object

要格式化的第二個物件。The second object to format.

arg2
Object Object Object Object

要格式化的第三個物件。The third object to format.

傳回

format 的複本,其中的格式項目已由 arg0arg1arg2 的字串表示取代。A copy of format in which the format items have been replaced by the string representations of arg0, arg1, and arg2.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引小於零或大於二。The index of a format item is less than zero, or greater than two.

備註

重要

請不要呼叫 String.Format 方法或使用複合格式字串,您可以使用「內插字串」 (如果您的語言支援它們的話)。Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. 內插字串是包含「插入運算式」 的字串。An interpolated string is a string that contains interpolated expressions. 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. 如需詳細資訊,請參閱內插字串 (C# 參考)內插字串 (Visual Basic 參考)For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

這個方法會使用複合格式功能將三個運算式轉換成其字串表示法,並內嵌在字串中的那些表示法。This method uses the composite formatting feature to convert three expressions to their string representations and to embed those representations in a string. 在執行轉換,該方法會使用區分文化特性格式,或自訂格式器。In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. 方法會將每個Object引數為其字串表示,藉由呼叫其ToString(IFormatProvider) 方法或,如果物件的對應格式項目會包含格式字串,藉由呼叫其ToString(String,IFormatProvider) 方法。The method converts each Object argument to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. 如果這些方法不存在,則會呼叫物件的無參數ToString方法。If these methods don't exist, it calls the object's parameterless ToString method.

不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. 相反地,您可以使用提供區分文化特性或自訂格式的物件和包含一或多個格式項目的複合格式字串來呼叫該方法。Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。You assign each format item a numeric index; the first index starts at 0. 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。In addition to the initial string, your method call should have as many additional arguments as it has index values. 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。Your language compiler will then resolve your method call to a particular overload of the String.Format method.

如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門要呼叫哪個方法?For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.

適用於