StringBuilder.AppendFormat StringBuilder.AppendFormat StringBuilder.AppendFormat StringBuilder.AppendFormat Method

定義

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目會由對應之物件引數的字串表示所取代。Each format item is replaced by the string representation of a corresponding object argument.

多載

AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 使用指定的格式提供者,將每個格式項目取代為三個引數中的其中一個字串表示。Each format item is replaced by the string representation of either of three arguments using a specified format provider.

AppendFormat(String, Object) AppendFormat(String, Object) AppendFormat(String, Object) AppendFormat(String, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目都會取代為單一引數的字串表示。Each format item is replaced by the string representation of a single argument.

AppendFormat(String, Object[]) AppendFormat(String, Object[]) AppendFormat(String, Object[]) AppendFormat(String, Object[])

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目會由參數陣列中對應之引數的字串表示所取代。Each format item is replaced by the string representation of a corresponding argument in a parameter array.

AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 使用指定的格式提供者,將每個格式項目取代為單一引數的字串表示。Each format item is replaced by the string representation of a single argument using a specified format provider.

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

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目會由參數陣列 (此參數陣列使用所指定的格式提供者) 中對應之物件引數的字串表示所取代。Each format item is replaced by the string representation of a corresponding argument in a parameter array using a specified format provider.

AppendFormat(String, Object, Object) AppendFormat(String, Object, Object) AppendFormat(String, Object, Object) AppendFormat(String, Object, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目都會取代為兩個引數中任一個的字串表示。Each format item is replaced by the string representation of either of two arguments.

AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 使用指定的格式提供者,將每個格式項目取代為兩個引數中的其中一個字串表示。Each format item is replaced by the string representation of either of two arguments using a specified format provider.

AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目都會取代為三個引數中任一個的字串表示。Each format item is replaced by the string representation of either of three arguments.

AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 使用指定的格式提供者,將每個格式項目取代為三個引數中的其中一個字串表示。Each format item is replaced by the string representation of either of three arguments using a specified format provider.

public:
 System::Text::StringBuilder ^ AppendFormat(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public System.Text.StringBuilder AppendFormat (IFormatProvider provider, string format, object arg0, object arg1, object arg2);
member this.AppendFormat : IFormatProvider * string * obj * obj * obj -> System.Text.StringBuilder
Public Function AppendFormat (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object, arg2 As Object) As StringBuilder

參數

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

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

format
String String String String

複合格式字串。A composite format 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.

傳回

完成附加作業之後,這個執行個體的參考。A reference to this instance after the append operation has completed. 在附加作業之後,此執行個體會包含此作業之前已存在的所有資料,並後置有 format 的複本,其中的任何格式規格都會由對應物件引數的字串表示所取代。After the append operation, this instance contains any data that existed before the operation, suffixed by a copy of format where any format specification is replaced by the string representation of the corresponding object argument.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引小於 0 (零) 或大於等於 3 (三)。The index of a format item is less than 0 (zero), or greater than or equal to 3 (three).

展開後的字串長度會超過 MaxCapacityThe length of the expanded string would exceed MaxCapacity.

範例

下列範例會使用AppendFormat(IFormatProvider, String, Object, Object, Object)方法來說明具有整數值之布林And運算的結果。The following example uses the AppendFormat(IFormatProvider, String, Object, Object, Object) method to illustrate the result of a Boolean And operation with integer values. 請注意,格式字串包含六個格式專案,但方法在其引數清單中只有三個專案,因為每個專案都是以兩種不同的方式進行格式化。Note that the format string includes six format items, but the method has only three items in its argument list, because each item is formatted in two different ways.

using System;
using System.Globalization;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      CultureInfo culture = CultureInfo.CreateSpecificCulture("fr-FR");
      StringBuilder sb = new StringBuilder();
      string formatString = "    {0,12:N0} ({0,8:X8})\n" +
                            "And {1,12:N0} ({1,8:X8})\n" +
                            "  = {2,12:N0} ({2,8:X8})\n";
      for (int ctr = 0; ctr <= 2; ctr++) {
         int value1 = rnd.Next();
         int value2 = rnd.Next();
         sb.AppendFormat(culture, formatString,
                         value1, value2, value1 & value2).
                         AppendLine();
      }
      Console.WriteLine(sb.ToString());
   }
}
// The example displays output like the following:
//           1 984 112 195 (76432643)
//       And 1 179 778 511 (4651FDCF)
//         = 1 178 674 243 (46412443)
//
//           2 034 813 710 (7948CB0E)
//       And  569 333 976 (21EF58D8)
//         =  558 385 160 (21484808)
//
//            126 717 735 (078D8F27)
//       And 1 830 715 973 (6D1E8245)
//         =   84 705 797 (050C8205)
Imports System.Globalization
Imports System.Text

Public Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("fr-FR")
      Dim sb As New StringBuilder()
      Dim formatString As String = "    {0,12:N0} ({0,8:X8})" + vbCrLf +
                                   "And {1,12:N0} ({1,8:X8})" + vbCrLf +
                                   "  = {2,12:N0} ({2,8:X8})" + vbCrLf
      For ctr As Integer = 0 To 2
         Dim value1 As Integer = rnd.Next()
         Dim value2 As Integer = rnd.Next()
         sb.AppendFormat(culture, formatString,
                         value1, value2, value1 And value2).AppendLine()
      Next
      Console.WriteLine(sb.ToString())
   End Sub
End Module
' The example displays the following output:
'           1 984 112 195 (76432643)
'       And 1 179 778 511 (4651FDCF)
'         = 1 178 674 243 (46412443)
'
'           2 034 813 710 (7948CB0E)
'       And  569 333 976 (21EF58D8)
'         =  558 385 160 (21484808)
'
'            126 717 735 (078D8F27)
'       And 1 830 715 973 (6D1E8245)
'         =   84 705 797 (050C8205)

備註

這個方法會使用 .NET Framework 的複合格式功能,將物件的值轉換成它的文字表示,並在目前StringBuilder的物件中內嵌該標記法。This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.

format參數包含零個或多個與零或多個索引預留位置(稱為格式專案)混合的文字,其對應于此方法的參數清單中的物件。The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to objects in the parameter list of this method. 格式化程式會將每個格式專案取代為對應物件的字串表示。The formatting process replaces each format item with the string representation of the corresponding object.

格式專案的語法如下:The syntax of a format item is as follows:

{index[,length] [:格式字串]}{index[,length][:formatString]}

在方括號中的元素是選擇性的元素。Elements in square brackets are optional. 下表說明每個元素。The following table describes each element.

元素Element 說明Description
indexindex 要格式化之物件的參數清單中以零為起始的位置。The zero-based position in the parameter list of the object to be formatted. 如果index所指定的物件是null,則會將格式String.Empty專案取代為。If the object specified by index is null, the format item is replaced by String.Empty. 如果索引位置中沒有參數, FormatException則會擲回。If there is no parameter in the index position, a FormatException is thrown.
length,length 參數的字串表示中的最小字元數。The minimum number of characters in the string representation of the parameter. 如果是正數,則參數會靠右對齊;如果是負數,則會靠左對齊。If positive, the parameter is right-aligned; if negative, it is left-aligned.
:formatString:formatString 參數所支援的標準或自訂格式字串。A standard or custom format string that is supported by the parameter.

注意

如需搭配日期和時間值使用的標準和自訂格式字串,請參閱標準日期和時間格式字串自訂日期和時間格式字串For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如需搭配數值使用的標準和自訂格式字串,請參閱標準數值格式字串自訂數值格式字串For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. 如需搭配列舉使用的標準格式字串,請參閱列舉格式字串For the standard format strings used with enumerations, see Enumeration Format Strings.

參數會指定可提供和arg0 arg1格式資訊的執行。IFormatProvider providerThe provider parameter specifies an IFormatProvider implementation that can provide formatting information for arg0 and arg1. provider 可以是下列任何項目:provider can be any of the following:

  • CultureInfo物件,提供特定文化特性格式資訊。A CultureInfo object that provides culture-specific formatting information.

  • 物件, arg0 提供arg1的特定文化特性格式資訊,如果是數值,則為。 NumberFormatInfoA NumberFormatInfo object that provides culture-specific formatting information for arg0 or arg1 if they are numeric values.

  • 物件,如果是日期和時間值,則arg0提供arg1、或arg2的特定文化特性格式資訊。 DateTimeFormatInfoA DateTimeFormatInfo object that provides culture-specific formatting information for arg0, arg1, or arg2 if they are date and time values.

  • 自訂IFormatProvider的執行,可提供、 arg0 arg1arg2的格式資訊。A custom IFormatProvider implementation that provides formatting information for arg0, arg1, and arg2. 一般來說,這類的實作為也ICustomFormatter會執行介面。Typically, such an implementation also implements the ICustomFormatter interface.

如果參數為null,則會從目前的文化特性取得格式提供者資訊。 providerIf the provider parameter is null, format provider information is obtained from the current culture.

arg0arg1arg2代表要格式化的物件。arg0, arg1, and arg2 represent the objects to be formatted. format的每個格式專案都會取代為具有對應索引之物件的字串表示。Each format item in format is replaced with the string representation of the object that has the corresponding index. 如果格式專案包含formatString ,且對應的引數IFormattable會執行介面,則引數ToString(formatString, provider)的方法會定義格式。If the format item includes formatString and the corresponding argument implements the IFormattable interface, then the argument's ToString(formatString, provider) method defines the formatting. 否則,引數的ToString()方法會定義格式。Otherwise, the argument's ToString() method defines the formatting.

給呼叫者的注意事項

在 .net Core 和 .NET Framework 4.0 和更新版本中,當您藉由呼叫StringBuilderStringBuilder(Int32, Int32)函式來具現化物件時, StringBuilder實例的長度和容量都可以成長超過其MaxCapacity的值property.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. 當您呼叫Append(String)AppendFormat(String, Object)方法來附加小型字串時,可能會發生這種情況。This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

另請參閱

AppendFormat(String, Object) AppendFormat(String, Object) AppendFormat(String, Object) AppendFormat(String, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目都會取代為單一引數的字串表示。Each format item is replaced by the string representation of a single argument.

public:
 System::Text::StringBuilder ^ AppendFormat(System::String ^ format, System::Object ^ arg0);
public System.Text.StringBuilder AppendFormat (string format, object arg0);
member this.AppendFormat : string * obj -> System.Text.StringBuilder
Public Function AppendFormat (format As String, arg0 As Object) As StringBuilder

參數

format
String String String String

複合格式字串。A composite format string.

arg0
Object Object Object Object

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

傳回

附加 format 的執行個體參考。A reference to this instance with format appended. format 中的每一個格式項目都會取代為 arg0 的字串表示。Each format item in format is replaced by the string representation of arg0.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引小於 0 (零) 或大於等於 1。The index of a format item is less than 0 (zero), or greater than or equal to 1.

展開後的字串長度會超過 MaxCapacityThe length of the expanded string would exceed MaxCapacity.

範例

下列範例示範AppendFormat方法。The following example demonstrates the AppendFormat method.

using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
   Console::WriteLine( sbs );
   sbs->Length = 0;
}

int main()
{
   StringBuilder^ sb = gcnew StringBuilder;
   int var1 = 111;
   float var2 = 2.22F;
   String^ var3 = "abcd";
   array<Object^>^var4 = {3,4.4,(Char)'X'};
   Console::WriteLine();
   Console::WriteLine( "StringBuilder.AppendFormat method:" );
   sb->AppendFormat( "1) {0}", var1 );
   Show( sb );
   sb->AppendFormat( "2) {0}, {1}", var1, var2 );
   Show( sb );
   sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
   Show( sb );
   sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
   Show( sb );
   CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
   array<Object^>^temp1 = {var2};
   sb->AppendFormat( ci, "5) {0}", temp1 );
   Show( sb );
}

/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;

class Sample 
{
    static StringBuilder sb = new StringBuilder();

    public static void Main() 
    {
    int    var1   = 111;
    float  var2   = 2.22F;
    string var3   = "abcd";
    object[] var4 = {3, 4.4, 'X'};

    Console.WriteLine();
    Console.WriteLine("StringBuilder.AppendFormat method:");
    sb.AppendFormat("1) {0}", var1);
    Show(sb);
    sb.AppendFormat("2) {0}, {1}", var1, var2);
    Show(sb);
    sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
    Show(sb);
    sb.AppendFormat("4) {0}, {1}, {2}", var4);
    Show(sb);
    CultureInfo ci = new CultureInfo("es-ES", true);
    sb.AppendFormat(ci, "5) {0}", var2);
    Show(sb);
    }

    public static void Show(StringBuilder sbs)
    {
    Console.WriteLine(sbs.ToString());
    sb.Length = 0;
    }
}
/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization

Class Sample
   Private Shared sb As New StringBuilder()

   Public Shared Sub Main()
      Dim var1 As Integer = 111
      Dim var2 As Single = 2.22F
      Dim var3 As String = "abcd"
      Dim var4 As Object() =  {3, 4.4, "X"c}
      
      Console.WriteLine()
      Console.WriteLine("StringBuilder.AppendFormat method:")
      sb.AppendFormat("1) {0}", var1)
      Show(sb)
      sb.AppendFormat("2) {0}, {1}", var1, var2)
      Show(sb)
      sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
      Show(sb)
      sb.AppendFormat("4) {0}, {1}, {2}", var4)
      Show(sb)
      Dim ci As New CultureInfo("es-ES", True)
      sb.AppendFormat(ci, "5) {0}", var2)
      Show(sb)
   End Sub
   
   Public Shared Sub Show(sbs As StringBuilder)
      Console.WriteLine(sbs.ToString())
      sb.Length = 0
   End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22

備註

這個方法會使用 .NET Framework 的複合格式功能,將物件的值轉換成它的文字表示,並在目前StringBuilder的物件中內嵌該標記法。This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.

format參數包含零個或多個與零或多個索引預留位置(稱為格式專案)混合的文字執行。The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items. 格式專案的索引必須為0,以對應至arg0這個方法之參數清單中的單一物件。The index of the format items must be 0, to correspond to arg0, the single object in the parameter list of this method. 格式化程式會將每個格式專案取代為的字串arg0表示。The formatting process replaces each format item with the string representation of arg0.

格式專案的語法如下:The syntax of a format item is as follows:

{index[,length] [:格式字串]}{index[,length][:formatString]}

在方括號中的元素是選擇性的元素。Elements in square brackets are optional. 下表說明每個元素。The following table describes each element.

元素Element 說明Description
indexindex 要格式化之物件的參數清單中以零為起始的位置。The zero-based position in the parameter list of the object to be formatted. 如果index所指定的物件是null,則會將格式String.Empty專案取代為。If the object specified by index is null, the format item is replaced by String.Empty. 如果索引位置中沒有參數, FormatException則會擲回。If there is no parameter in the index position, a FormatException is thrown.
length,length 參數的字串表示中的最小字元數。The minimum number of characters in the string representation of the parameter. 如果是正數,則參數會靠右對齊;如果是負數,則會靠左對齊。If positive, the parameter is right-aligned; if negative, it is left-aligned.
:formatString:formatString 參數所支援的標準或自訂格式字串。A standard or custom format string that is supported by the parameter.

注意

如需搭配日期和時間值使用的標準和自訂格式字串,請參閱標準日期和時間格式字串自訂日期和時間格式字串For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如需搭配數值使用的標準和自訂格式字串,請參閱標準數值格式字串自訂數值格式字串For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. 如需搭配列舉使用的標準格式字串,請參閱列舉格式字串For the standard format strings used with enumerations, see Enumeration Format Strings.

arg0表示要格式化的物件。arg0 represents the object to be formatted. format的每個格式專案都會取代為的字串arg0表示。Each format item in format is replaced with the string representation of arg0. 如果格式專案formatString包含並arg0 IFormattable執行介面,則arg0.ToString(formatString, null)會定義格式。If the format item includes formatString and arg0 implements the IFormattable interface, then arg0.ToString(formatString, null) defines the formatting. 否則, arg0.ToString()會定義格式。Otherwise, arg0.ToString() defines the formatting.

如果指派給format的字串是「感謝您將 {0: # # # #} 的食物捐贈給我們的慈善組織。」If the string assigned to format is "Thank you for your donation of {0:####} cans of food to our charitable organization." arg0是值為10的整數,傳回值將會是「感謝您捐贈10罐的食物給我們的慈善組織。」and arg0 is an integer with the value 10, the return value will be "Thank you for your donation of 10 cans of food to our charitable organization."

給呼叫者的注意事項

在 .net Core 和 .NET Framework 4.0 和更新版本中,當您藉由呼叫StringBuilderStringBuilder(Int32, Int32)函式來具現化物件時, StringBuilder實例的長度和容量都可以成長超過其MaxCapacity的值property.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. 當您呼叫Append(String)AppendFormat(String, Object)方法來附加小型字串時,可能會發生這種情況。This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

另請參閱

AppendFormat(String, Object[]) AppendFormat(String, Object[]) AppendFormat(String, Object[]) AppendFormat(String, Object[])

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目會由參數陣列中對應之引數的字串表示所取代。Each format item is replaced by the string representation of a corresponding argument in a parameter array.

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

參數

format
String String String String

複合格式字串。A composite format string.

args
Object[]

要格式化的物件陣列。An array of objects to format.

傳回

附加 format 的執行個體參考。A reference to this instance with format appended. format 中的每一個格式項目會由對應之物件引數的字串表示所取代。Each format item in format is replaced by the string representation of the corresponding object argument.

例外狀況

formatargsnullformat or args is null.

format 無效。format is invalid.

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

展開後的字串長度會超過 MaxCapacityThe length of the expanded string would exceed MaxCapacity.

範例

下列範例示範AppendFormat方法。The following example demonstrates the AppendFormat method.

using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
   Console::WriteLine( sbs );
   sbs->Length = 0;
}

int main()
{
   StringBuilder^ sb = gcnew StringBuilder;
   int var1 = 111;
   float var2 = 2.22F;
   String^ var3 = "abcd";
   array<Object^>^var4 = {3,4.4,(Char)'X'};
   Console::WriteLine();
   Console::WriteLine( "StringBuilder.AppendFormat method:" );
   sb->AppendFormat( "1) {0}", var1 );
   Show( sb );
   sb->AppendFormat( "2) {0}, {1}", var1, var2 );
   Show( sb );
   sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
   Show( sb );
   sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
   Show( sb );
   CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
   array<Object^>^temp1 = {var2};
   sb->AppendFormat( ci, "5) {0}", temp1 );
   Show( sb );
}

/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;

class Sample 
{
    static StringBuilder sb = new StringBuilder();

    public static void Main() 
    {
    int    var1   = 111;
    float  var2   = 2.22F;
    string var3   = "abcd";
    object[] var4 = {3, 4.4, 'X'};

    Console.WriteLine();
    Console.WriteLine("StringBuilder.AppendFormat method:");
    sb.AppendFormat("1) {0}", var1);
    Show(sb);
    sb.AppendFormat("2) {0}, {1}", var1, var2);
    Show(sb);
    sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
    Show(sb);
    sb.AppendFormat("4) {0}, {1}, {2}", var4);
    Show(sb);
    CultureInfo ci = new CultureInfo("es-ES", true);
    sb.AppendFormat(ci, "5) {0}", var2);
    Show(sb);
    }

    public static void Show(StringBuilder sbs)
    {
    Console.WriteLine(sbs.ToString());
    sb.Length = 0;
    }
}
/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization

Class Sample
   Private Shared sb As New StringBuilder()

   Public Shared Sub Main()
      Dim var1 As Integer = 111
      Dim var2 As Single = 2.22F
      Dim var3 As String = "abcd"
      Dim var4 As Object() =  {3, 4.4, "X"c}
      
      Console.WriteLine()
      Console.WriteLine("StringBuilder.AppendFormat method:")
      sb.AppendFormat("1) {0}", var1)
      Show(sb)
      sb.AppendFormat("2) {0}, {1}", var1, var2)
      Show(sb)
      sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
      Show(sb)
      sb.AppendFormat("4) {0}, {1}, {2}", var4)
      Show(sb)
      Dim ci As New CultureInfo("es-ES", True)
      sb.AppendFormat(ci, "5) {0}", var2)
      Show(sb)
   End Sub
   
   Public Shared Sub Show(sbs As StringBuilder)
      Console.WriteLine(sbs.ToString())
      sb.Length = 0
   End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22

備註

這個方法會使用 .NET Framework 的複合格式功能,將物件的值轉換成它的文字表示,並在目前StringBuilder的物件中內嵌該標記法。This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.

format參數包含零個或多個與零或多個索引預留位置(稱為格式專案)混合的文字,其對應于此方法的參數清單中的物件。The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to objects in the parameter list of this method. 格式化程式會將每個格式專案取代為對應物件的字串表示。The formatting process replaces each format item with the string representation of the corresponding object.

格式專案的語法如下:The syntax of a format item is as follows:

{index[,length] [:格式字串]}{index[,length][:formatString]}

在方括號中的元素是選擇性的元素。Elements in square brackets are optional. 下表說明每個元素。The following table describes each element.

元素Element 說明Description
indexindex 要格式化之物件的參數清單中以零為起始的位置。The zero-based position in the parameter list of the object to be formatted. 如果index所指定的物件是null,則會將格式String.Empty專案取代為。If the object specified by index is null, the format item is replaced by String.Empty. 如果索引位置中沒有參數, FormatException則會擲回。If there is no parameter in the index position, a FormatException is thrown.
length,length 參數的字串表示中的最小字元數。The minimum number of characters in the string representation of the parameter. 如果是正數,則參數會靠右對齊;如果是負數,則會靠左對齊。If positive, the parameter is right-aligned; if negative, it is left-aligned.
:formatString:formatString 參數所支援的標準或自訂格式字串。A standard or custom format string that is supported by the parameter.

注意

如需搭配日期和時間值使用的標準和自訂格式字串,請參閱標準日期和時間格式字串自訂日期和時間格式字串For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如需搭配數值使用的標準和自訂格式字串,請參閱標準數值格式字串自訂數值格式字串For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. 如需搭配列舉使用的標準格式字串,請參閱列舉格式字串For the standard format strings used with enumerations, see Enumeration Format Strings.

args表示要格式化的物件。args represents the objects to be formatted. format的每個格式專案都會取代為中args對應物件的字串表示。Each format item in format is replaced with the string representation of the corresponding object in args. formatString如果格式專案包含,且中args IFormattable的對應物件會執行介面,則args[index].ToString(formatString, provider)會定義格式。If the format item includes formatString and the corresponding object in args implements the IFormattable interface, then args[index].ToString(formatString, provider) defines the formatting. 否則, args[index].ToString()會定義格式。Otherwise, args[index].ToString() defines the formatting.

如果指派給format的字串是「感謝您將 {0: # # # #} 的食物捐贈給我們的慈善組織。」If the string assigned to format is "Thank you for your donation of {0:####} cans of food to our charitable organization." arg0是值為10的整數,傳回值將會是「感謝您捐贈10罐的食物給我們的慈善組織。」and arg0 is an integer with the value 10, the return value will be "Thank you for your donation of 10 cans of food to our charitable organization."

給呼叫者的注意事項

在 .net Core 和 .NET Framework 4.0 和更新版本中,當您藉由呼叫StringBuilderStringBuilder(Int32, Int32)函式來具現化物件時, StringBuilder實例的長度和容量都可以成長超過其MaxCapacity的值property.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. 當您呼叫Append(String)AppendFormat(String, Object)方法來附加小型字串時,可能會發生這種情況。This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

另請參閱

AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 使用指定的格式提供者,將每個格式項目取代為單一引數的字串表示。Each format item is replaced by the string representation of a single argument using a specified format provider.

public:
 System::Text::StringBuilder ^ AppendFormat(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0);
public System.Text.StringBuilder AppendFormat (IFormatProvider provider, string format, object arg0);
member this.AppendFormat : IFormatProvider * string * obj -> System.Text.StringBuilder
Public Function AppendFormat (provider As IFormatProvider, format As String, arg0 As Object) As StringBuilder

參數

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

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

format
String String String String

複合格式字串。A composite format string.

arg0
Object Object Object Object

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

傳回

完成附加作業之後,這個執行個體的參考。A reference to this instance after the append operation has completed. 在附加作業之後,這個執行個體會包含作業前已經存在的所有資料,並後置有 format 的複本,其中的任何格式規格都會由 arg0 的字串表示所取代。After the append operation, this instance contains any data that existed before the operation, suffixed by a copy of format in which any format specification is replaced by the string representation of arg0.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引小於 0 (零) 或大於等於 1。The index of a format item is less than 0 (zero), or greater than or equal to one (1).

展開後的字串長度會超過 MaxCapacityThe length of the expanded string would exceed MaxCapacity.

範例

以下包含對AppendFormat(IFormatProvider, String, Object)方法的兩個呼叫。The following includes two calls to the AppendFormat(IFormatProvider, String, Object) method. 兩者都使用英文-英國(en-GB)文化特性的格式化慣例。Both use the formatting conventions of the English-Great Britain (en-GB) culture. 第一個會在結果字串中插入Decimal值貨幣的字串表示。The first inserts the string representation of a Decimal value currency in a result string. 第二個會DateTime在結果字串中的兩個位置插入一個值,第一個只包含簡短的日期字串,而第二個是簡短的時間字串。The second inserts a DateTime value in two places in a result string, the first including only the short date string and the second the short time string.

using System;
using System.Globalization;
using System.Text;

public class Example
{
   public static void Main()
   {
      StringBuilder sb = new StringBuilder();
      Decimal value = 16.95m;
      CultureInfo enGB = CultureInfo.CreateSpecificCulture("en-GB");
      DateTime dateToday = DateTime.Now;
      sb.AppendFormat(enGB, "Final Price: {0:C2}", value);
      sb.AppendLine();
      sb.AppendFormat(enGB, "Date and Time: {0:d} at {0:t}", dateToday);
      Console.WriteLine(sb.ToString());
   }
}
// The example displays the following output:
//       Final Price: £16.95
//       Date and Time: 01/10/2014 at 10:22
Imports System.Globalization
Imports System.Text

Module Example
   Public Sub Main()
      Dim sb As New StringBuilder()
      Dim value As Decimal = 16.95d
      Dim enGB As CultureInfo = CultureInfo.CreateSpecificCulture("en-GB")
      Dim dateToday As DateTime = Date.Now
      sb.AppendFormat(enGB, "Final Price: {0:C2}", value)
      sb.AppendLine()
      sb.AppendFormat(enGB, "Date and Time: {0:d} at {0:t}", dateToday)
      Console.WriteLine(sb.ToString())
   End Sub
End Module
' The example displays output like the following:
'       Final Price: £16.95
'       Date and Time: 01/10/2014 at 10:22

備註

這個方法會使用 .NET Framework 的複合格式功能,將的值arg0轉換為其文字表示,並在目前StringBuilder的物件中內嵌該標記法。This method uses the composite formatting feature of the .NET Framework to convert the value of arg0 to its text representation and embed that representation in the current StringBuilder object.

format參數包含零個或多個與零或多個索引預留位置(稱為格式專案)混合的文字執行。The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items. 每個格式專案的索引都必須為零(0),因為這個方法包含具有單一引數的引數清單。The index of each format item must be zero (0) since this method includes an argument list with a single argument. 格式化程式會將每個格式專案取代為的字串arg0表示。The formatting process replaces each format item with the string representation of arg0.

格式專案的語法如下:The syntax of a format item is as follows:

{index[,length] [:格式字串]}{index[,length][:formatString]}

在方括號中的元素是選擇性的元素。Elements in square brackets are optional. 下表說明每個元素。The following table describes each element.

元素Element 說明Description
indexindex 要格式化之物件的參數清單中以零為起始的位置。The zero-based position in the parameter list of the object to be formatted. 如果index所指定的物件是null,則會將格式String.Empty專案取代為。If the object specified by index is null, the format item is replaced by String.Empty. 在此情況下,因為AppendFormat(IFormatProvider, String, Object)方法在引數清單中具有單一引數,所以index的值必須一律為0。In this case, since the AppendFormat(IFormatProvider, String, Object) method has a single argument in the argument list, the value of index must always be 0. 如果不是, FormatException則會擲回。If it is not, a FormatException is thrown.
length,length 參數的字串表示中的最小字元數。The minimum number of characters in the string representation of the parameter. 如果是正數,則參數會靠右對齊;如果是負數,則會靠左對齊。If positive, the parameter is right-aligned; if negative, it is left-aligned.
:formatString:formatString 參數所支援的標準或自訂格式字串。A standard or custom format string that is supported by the parameter.

注意

如需搭配日期和時間值使用的標準和自訂格式字串,請參閱標準日期和時間格式字串自訂日期和時間格式字串For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如需搭配數值使用的標準和自訂格式字串,請參閱標準數值格式字串自訂數值格式字串For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. 如需搭配列舉使用的標準格式字串,請參閱列舉格式字串For the standard format strings used with enumerations, see Enumeration Format Strings.

參數會指定可在中args提供物件格式資訊的執行。IFormatProvider providerThe provider parameter specifies an IFormatProvider implementation that can provide formatting information for the objects in args. provider 可以是下列任何項目:provider can be any of the following:

  • CultureInfo物件,提供特定文化特性格式資訊。A CultureInfo object that provides culture-specific formatting information.

  • 物件,如果它是數值,則提供的arg0特定文化特性格式資訊。 NumberFormatInfoA NumberFormatInfo object that provides culture-specific formatting information for arg0 if it is a numeric value.

  • 物件,如果它是日期和時間值, arg0則提供的特定文化特性格式資訊。 DateTimeFormatInfoA DateTimeFormatInfo object that provides culture-specific formatting information for arg0 if it is a date and time value.

  • 提供之IFormatProvider格式arg0資訊的自訂執行。A custom IFormatProvider implementation that provides formatting information for arg0. 一般來說,這類的實作為也ICustomFormatter會執行介面。Typically, such an implementation also implements the ICustomFormatter interface.

如果參數為null,則會從目前的文化特性取得格式資訊。 providerIf the provider parameter is null, formatting information is obtained from the current culture.

arg0表示要格式化的物件。arg0 represents the object to be formatted. format的每個格式專案都會取代為的字串arg0表示。Each format item in format is replaced with the string representation of arg0. 如果格式專案formatString包含並arg0 IFormattable執行介面,則arg0.ToString(formatString, provider)會定義格式。If the format item includes formatString and arg0 implements the IFormattable interface, then arg0.ToString(formatString, provider) defines the formatting. 否則, arg0.ToString()會定義格式。Otherwise, arg0.ToString() defines the formatting.

給呼叫者的注意事項

在 .net Core 和 .NET Framework 4.0 和更新版本中,當您藉由呼叫StringBuilderStringBuilder(Int32, Int32)函式來具現化物件時, StringBuilder實例的長度和容量都可以成長超過其MaxCapacity的值property.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. 當您呼叫Append(String)AppendFormat(String, Object)方法來附加小型字串時,可能會發生這種情況。This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

另請參閱

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

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目會由參數陣列 (此參數陣列使用所指定的格式提供者) 中對應之物件引數的字串表示所取代。Each format item is replaced by the string representation of a corresponding argument in a parameter array using a specified format provider.

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

參數

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

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

format
String String String String

複合格式字串。A composite format string.

args
Object[]

要格式化的物件陣列。An array of objects to format.

傳回

完成附加作業之後,這個執行個體的參考。A reference to this instance after the append operation has completed. 在附加作業之後,此執行個體會包含此作業之前已存在的所有資料,並後置有 format 的複本,其中的任何格式規格都會由對應物件引數的字串表示所取代。After the append operation, this instance contains any data that existed before the operation, suffixed by a copy of format where any format specification is replaced by the string representation of the corresponding object argument.

例外狀況

format 無效。format is invalid.

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

展開後的字串長度會超過 MaxCapacityThe length of the expanded string would exceed MaxCapacity.

範例

下列範例示範AppendFormat方法。The following example demonstrates the AppendFormat method.

using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
   Console::WriteLine( sbs );
   sbs->Length = 0;
}

int main()
{
   StringBuilder^ sb = gcnew StringBuilder;
   int var1 = 111;
   float var2 = 2.22F;
   String^ var3 = "abcd";
   array<Object^>^var4 = {3,4.4,(Char)'X'};
   Console::WriteLine();
   Console::WriteLine( "StringBuilder.AppendFormat method:" );
   sb->AppendFormat( "1) {0}", var1 );
   Show( sb );
   sb->AppendFormat( "2) {0}, {1}", var1, var2 );
   Show( sb );
   sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
   Show( sb );
   sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
   Show( sb );
   CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
   array<Object^>^temp1 = {var2};
   sb->AppendFormat( ci, "5) {0}", temp1 );
   Show( sb );
}

/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;

class Sample 
{
    static StringBuilder sb = new StringBuilder();

    public static void Main() 
    {
    int    var1   = 111;
    float  var2   = 2.22F;
    string var3   = "abcd";
    object[] var4 = {3, 4.4, 'X'};

    Console.WriteLine();
    Console.WriteLine("StringBuilder.AppendFormat method:");
    sb.AppendFormat("1) {0}", var1);
    Show(sb);
    sb.AppendFormat("2) {0}, {1}", var1, var2);
    Show(sb);
    sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
    Show(sb);
    sb.AppendFormat("4) {0}, {1}, {2}", var4);
    Show(sb);
    CultureInfo ci = new CultureInfo("es-ES", true);
    sb.AppendFormat(ci, "5) {0}", var2);
    Show(sb);
    }

    public static void Show(StringBuilder sbs)
    {
    Console.WriteLine(sbs.ToString());
    sb.Length = 0;
    }
}
/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization

Class Sample
   Private Shared sb As New StringBuilder()

   Public Shared Sub Main()
      Dim var1 As Integer = 111
      Dim var2 As Single = 2.22F
      Dim var3 As String = "abcd"
      Dim var4 As Object() =  {3, 4.4, "X"c}
      
      Console.WriteLine()
      Console.WriteLine("StringBuilder.AppendFormat method:")
      sb.AppendFormat("1) {0}", var1)
      Show(sb)
      sb.AppendFormat("2) {0}, {1}", var1, var2)
      Show(sb)
      sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
      Show(sb)
      sb.AppendFormat("4) {0}, {1}, {2}", var4)
      Show(sb)
      Dim ci As New CultureInfo("es-ES", True)
      sb.AppendFormat(ci, "5) {0}", var2)
      Show(sb)
   End Sub
   
   Public Shared Sub Show(sbs As StringBuilder)
      Console.WriteLine(sbs.ToString())
      sb.Length = 0
   End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22

下列範例會定義名為IFormatProvider CustomerFormatter的自訂執行,以格式化10位數的客戶編碼,並在第四和第七個數字之後使用連字號。The following example defines a custom IFormatProvider implementation named CustomerFormatter that formats a 10-digit customer number with hyphens after the fourth and seventh digits. 它會傳遞至StringBuilder.AppendFormat(IFormatProvider, String, Object[])方法,以建立字串,其中包含已格式化的客戶編碼和客戶名稱。It is passed to the StringBuilder.AppendFormat(IFormatProvider, String, Object[]) method to create a string that includes the formatted customer number and customer name.

using System;
using System.Text;

public class Customer
{
   private string custName;
   private int custNumber;
   
   public Customer(string name, int number)
   {
      this.custName = name;
      this.custNumber = number;
   }
   
   public string Name
   {
      get { return this.custName; }
   }
   
   public int CustomerNumber
   {
      get { return this.custNumber; }
   }
}

public class CustomerNumberFormatter : IFormatProvider, ICustomFormatter
{   
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      return null;
   }
   
   public string Format(string format, object arg, IFormatProvider provider)
   {
      if (arg is Int32)
      {
         string custNumber = ((int) arg).ToString("D10");
         return custNumber.Substring(0, 4) + "-" + custNumber.Substring(4, 3) + 
                "-" + custNumber.Substring(7, 3);
      }
      else
      {
         return null;
      }
   }                   
}

public class Example
{
   public static void Main()
   {
      Customer customer = new Customer("A Plus Software", 903654);
      StringBuilder sb = new StringBuilder();
      sb.AppendFormat(new CustomerNumberFormatter(), "{0}: {1}", 
                      customer.CustomerNumber, customer.Name);
      Console.WriteLine(sb.ToString());
   }
}
// The example displays the following output:
//      0000-903-654: A Plus Software
Imports System.Text

Public Class Customer
   Private custName As String
   Private custNumber As Integer
   
   Public Sub New(name As String, number As Integer)
      custName = name
      custNumber = number
   End Sub
   
   Public ReadOnly Property Name As String
      Get
         Return Me.custName
      End Get
   End Property
   
   Public ReadOnly Property CustomerNumber As Integer
      Get
         Return Me.custNumber
      End Get
   End Property
End Class

Public Class CustomerNumberFormatter 
   Implements IFormatProvider, ICustomFormatter
   
   Public Function GetFormat(formatType As Type) As Object _
                   Implements IFormatProvider.GetFormat
      If formatType Is GetType(ICustomFormatter) Then
         Return Me
      End If
      Return Nothing
   End Function
   
   Public Function Format(fmt As String, arg As Object, provider As IFormatProvider) As String _
                   Implements ICustomFormatter.Format
      If typeof arg Is Int32 Then
         Dim custNumber As String = CInt(arg).ToString("D10")
         Return custNumber.Substring(0, 4) + "-" + custNumber.SubString(4, 3) + _
                "-" + custNumber.Substring(7, 3)
      Else
         Return Nothing
      End If
   End Function                   
End Class

Module Example
   Public Sub Main()
      Dim customer As New Customer("A Plus Software", 903654)
      Dim sb As New StringBuilder()
      sb.AppendFormat(New CustomerNumberFormatter, "{0}: {1}", _
                      customer.CustomerNumber, customer.Name)
      Console.WriteLine(sb.ToString())
   End Sub
End Module
' The example displays the following output:
'      0000-903-654: A Plus Software

備註

這個方法會使用 .NET Framework 的複合格式功能,將物件的值轉換成它的文字表示,並在目前StringBuilder的物件中內嵌該標記法。This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.

format參數包含零個或多個與零或多個索引預留位置(稱為格式專案)混合的文字,其對應于此方法的參數清單中的物件。The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to objects in the parameter list of this method. 格式化程式會將每個格式專案取代為對應物件的字串表示。The formatting process replaces each format item with the string representation of the corresponding object.

格式專案的語法如下:The syntax of a format item is as follows:

{index[,length] [:格式字串]}{index[,length][:formatString]}

在方括號中的元素是選擇性的元素。Elements in square brackets are optional. 下表說明每個元素。The following table describes each element.

元素Element 說明Description
indexindex 要格式化之物件的參數清單中以零為起始的位置。The zero-based position in the parameter list of the object to be formatted. 如果index所指定的物件是null,則會將格式String.Empty專案取代為。If the object specified by index is null, the format item is replaced by String.Empty. 如果索引位置中沒有參數, FormatException則會擲回。If there is no parameter in the index position, a FormatException is thrown.
length,length 參數的字串表示中的最小字元數。The minimum number of characters in the string representation of the parameter. 如果是正數,則參數會靠右對齊;如果是負數,則會靠左對齊。If positive, the parameter is right-aligned; if negative, it is left-aligned.
:formatString:formatString 參數所支援的標準或自訂格式字串。A standard or custom format string that is supported by the parameter.

注意

如需搭配日期和時間值使用的標準和自訂格式字串,請參閱標準日期和時間格式字串自訂日期和時間格式字串For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如需搭配數值使用的標準和自訂格式字串,請參閱標準數值格式字串自訂數值格式字串For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. 如需搭配列舉使用的標準格式字串,請參閱列舉格式字串For the standard format strings used with enumerations, see Enumeration Format Strings.

參數會指定可在中args提供物件格式資訊的執行。IFormatProvider providerThe provider parameter specifies an IFormatProvider implementation that can provide formatting information for the objects in args. provider 可以是下列任何項目:provider can be any of the following:

如果參數為null,則會從目前的文化特性取得格式提供者資訊。 providerIf the provider parameter is null, format provider information is obtained from the current culture.

args表示要格式化的物件。args represents the objects to be formatted. format的每個格式專案都會取代為中args對應物件的字串表示。Each format item in format is replaced with the string representation of the corresponding object in args. formatString如果格式專案包含,且中args IFormattable的對應物件會執行介面,則args[index].ToString(formatString, provider)會定義格式。If the format item includes formatString and the corresponding object in args implements the IFormattable interface, then args[index].ToString(formatString, provider) defines the formatting. 否則, args[index].ToString()會定義格式。Otherwise, args[index].ToString() defines the formatting.

給呼叫者的注意事項

在 .net Core 和 .NET Framework 4.0 和更新版本中,當您藉由呼叫StringBuilderStringBuilder(Int32, Int32)函式來具現化物件時, StringBuilder實例的長度和容量都可以成長超過其MaxCapacity的值property.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. 當您呼叫Append(String)AppendFormat(String, Object)方法來附加小型字串時,可能會發生這種情況。This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

另請參閱

AppendFormat(String, Object, Object) AppendFormat(String, Object, Object) AppendFormat(String, Object, Object) AppendFormat(String, Object, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目都會取代為兩個引數中任一個的字串表示。Each format item is replaced by the string representation of either of two arguments.

public:
 System::Text::StringBuilder ^ AppendFormat(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public System.Text.StringBuilder AppendFormat (string format, object arg0, object arg1);
member this.AppendFormat : string * obj * obj -> System.Text.StringBuilder
Public Function AppendFormat (format As String, arg0 As Object, arg1 As Object) As StringBuilder

參數

format
String String String String

複合格式字串。A composite format string.

arg0
Object Object Object Object

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

arg1
Object Object Object Object

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

傳回

附加 format 的執行個體參考。A reference to this instance with format appended. format 中的每一個格式項目會由對應之物件引數的字串表示所取代。Each format item in format is replaced by the string representation of the corresponding object argument.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引小於 0 (零) 或大於等於 2。The index of a format item is less than 0 (zero), or greater than or equal to 2.

展開後的字串長度會超過 MaxCapacityThe length of the expanded string would exceed MaxCapacity.

範例

下列範例示範AppendFormat方法。The following example demonstrates the AppendFormat method.

using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
   Console::WriteLine( sbs );
   sbs->Length = 0;
}

int main()
{
   StringBuilder^ sb = gcnew StringBuilder;
   int var1 = 111;
   float var2 = 2.22F;
   String^ var3 = "abcd";
   array<Object^>^var4 = {3,4.4,(Char)'X'};
   Console::WriteLine();
   Console::WriteLine( "StringBuilder.AppendFormat method:" );
   sb->AppendFormat( "1) {0}", var1 );
   Show( sb );
   sb->AppendFormat( "2) {0}, {1}", var1, var2 );
   Show( sb );
   sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
   Show( sb );
   sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
   Show( sb );
   CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
   array<Object^>^temp1 = {var2};
   sb->AppendFormat( ci, "5) {0}", temp1 );
   Show( sb );
}

/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;

class Sample 
{
    static StringBuilder sb = new StringBuilder();

    public static void Main() 
    {
    int    var1   = 111;
    float  var2   = 2.22F;
    string var3   = "abcd";
    object[] var4 = {3, 4.4, 'X'};

    Console.WriteLine();
    Console.WriteLine("StringBuilder.AppendFormat method:");
    sb.AppendFormat("1) {0}", var1);
    Show(sb);
    sb.AppendFormat("2) {0}, {1}", var1, var2);
    Show(sb);
    sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
    Show(sb);
    sb.AppendFormat("4) {0}, {1}, {2}", var4);
    Show(sb);
    CultureInfo ci = new CultureInfo("es-ES", true);
    sb.AppendFormat(ci, "5) {0}", var2);
    Show(sb);
    }

    public static void Show(StringBuilder sbs)
    {
    Console.WriteLine(sbs.ToString());
    sb.Length = 0;
    }
}
/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization

Class Sample
   Private Shared sb As New StringBuilder()

   Public Shared Sub Main()
      Dim var1 As Integer = 111
      Dim var2 As Single = 2.22F
      Dim var3 As String = "abcd"
      Dim var4 As Object() =  {3, 4.4, "X"c}
      
      Console.WriteLine()
      Console.WriteLine("StringBuilder.AppendFormat method:")
      sb.AppendFormat("1) {0}", var1)
      Show(sb)
      sb.AppendFormat("2) {0}, {1}", var1, var2)
      Show(sb)
      sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
      Show(sb)
      sb.AppendFormat("4) {0}, {1}, {2}", var4)
      Show(sb)
      Dim ci As New CultureInfo("es-ES", True)
      sb.AppendFormat(ci, "5) {0}", var2)
      Show(sb)
   End Sub
   
   Public Shared Sub Show(sbs As StringBuilder)
      Console.WriteLine(sbs.ToString())
      sb.Length = 0
   End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22

備註

這個方法會使用 .NET Framework 的複合格式功能,將物件的值轉換成它的文字表示,並在目前StringBuilder的物件中內嵌該標記法。This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.

參數包含零個或多個與零或多個索引預留位置混合的文字,稱為格式專案,其對應于arg0arg1,這是此方法的參數清單中的兩個物件。 formatThe format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to arg0 and arg1, the two objects in the parameter list of this method. 格式化程式會將每個格式專案取代為對應物件的字串表示。The formatting process replaces each format item with the string representation of the corresponding object.

格式專案的語法如下:The syntax of a format item is as follows:

{index[,length] [:格式字串]}{index[,length][:formatString]}

在方括號中的元素是選擇性的元素。Elements in square brackets are optional. 下表說明每個元素。The following table describes each element.

元素Element 說明Description
indexindex 要格式化之物件的參數清單中以零為起始的位置。The zero-based position in the parameter list of the object to be formatted. 如果index所指定的物件是null,則會將格式String.Empty專案取代為。If the object specified by index is null, the format item is replaced by String.Empty. 如果索引位置中沒有參數, FormatException則會擲回。If there is no parameter in the index position, a FormatException is thrown.
length,length 參數的字串表示中的最小字元數。The minimum number of characters in the string representation of the parameter. 如果是正數,則參數會靠右對齊;如果是負數,則會靠左對齊。If positive, the parameter is right-aligned; if negative, it is left-aligned.
:formatString:formatString 參數所支援的標準或自訂格式字串。A standard or custom format string that is supported by the parameter.

注意

如需搭配日期和時間值使用的標準和自訂格式字串,請參閱標準日期和時間格式字串自訂日期和時間格式字串For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如需搭配數值使用的標準和自訂格式字串,請參閱標準數值格式字串自訂數值格式字串For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. 如需搭配列舉使用的標準格式字串,請參閱列舉格式字串For the standard format strings used with enumerations, see Enumeration Format Strings.

arg0arg1代表要格式化的物件。arg0 and arg1 represent the objects to be formatted. format的每個格式專案都會取代為arg0arg1的字串表示。Each format item in format is replaced with the string representation of either arg0 or arg1. 如果格式formatString專案包含,且對應的物件IFormattable會執行介面,則arg x .ToString(formatString, provider)會定義格式,其中x是引數的索引。If the format item includes formatString and the corresponding object implements the IFormattable interface, then argx.ToString(formatString, provider) defines the formatting, where x is the index of the argument. 否則, arg x.ToString()會定義格式。Otherwise, argx.ToString() defines the formatting.

如果指派給format的字串是「感謝您將 {0: # # # #} 的食物捐贈給我們的慈善組織。」If the string assigned to format is "Thank you for your donation of {0:####} cans of food to our charitable organization." arg0是值為10的整數,傳回值將會是「感謝您捐贈10罐的食物給我們的慈善組織。」and arg0 is an integer with the value 10, the return value will be "Thank you for your donation of 10 cans of food to our charitable organization."

給呼叫者的注意事項

在 .net Core 和 .NET Framework 4.0 和更新版本中,當您藉由呼叫StringBuilderStringBuilder(Int32, Int32)函式來具現化物件時, StringBuilder實例的長度和容量都可以成長超過其MaxCapacity的值property.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. 當您呼叫Append(String)AppendFormat(String, Object)方法來附加小型字串時,可能會發生這種情況。This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

另請參閱

AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 使用指定的格式提供者,將每個格式項目取代為兩個引數中的其中一個字串表示。Each format item is replaced by the string representation of either of two arguments using a specified format provider.

public:
 System::Text::StringBuilder ^ AppendFormat(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public System.Text.StringBuilder AppendFormat (IFormatProvider provider, string format, object arg0, object arg1);
member this.AppendFormat : IFormatProvider * string * obj * obj -> System.Text.StringBuilder
Public Function AppendFormat (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object) As StringBuilder

參數

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

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

format
String String String String

複合格式字串。A composite format string.

arg0
Object Object Object Object

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

arg1
Object Object Object Object

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

傳回

完成附加作業之後,這個執行個體的參考。A reference to this instance after the append operation has completed. 在附加作業之後,此執行個體會包含此作業之前已存在的所有資料,並後置有 format 的複本,其中的任何格式規格都會由對應物件引數的字串表示所取代。After the append operation, this instance contains any data that existed before the operation, suffixed by a copy of format where any format specification is replaced by the string representation of the corresponding object argument.

例外狀況

format 無效。format is invalid.

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

展開後的字串長度會超過 MaxCapacityThe length of the expanded string would exceed MaxCapacity.

範例

下列範例會使用AppendFormat(IFormatProvider, String, Object, Object)方法來顯示儲存在泛型Dictionary<TKey,TValue>物件中的時間和溫度資料。The following example uses the AppendFormat(IFormatProvider, 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 to 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 System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

public class Example
{
   public static void Main()
   {
      CultureInfo culture = new CultureInfo("en-US");
      StringBuilder sb = new StringBuilder();
      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);
      

      sb.AppendLine("Temperature Information:\n");
      foreach (var item in temperatureInfo)
      {
         sb.AppendFormat(culture,
                         "Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F\n",
                         item.Key, item.Value);
      }
      Console.WriteLine(sb.ToString());
   }
}
// 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
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Text

Module Example
   Public Sub Main()
      Dim culture As New CultureInfo("en-US")
      Dim sb As New StringBuilder()
      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)
      
      sb.AppendLine("Temperature Information:").AppendLine()
      For Each item In temperatureInfo
         sb.AppendFormat(culture,
                         "Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F",
                         item.Key, item.Value).AppendLine()
      Next
      Console.WriteLine(sb.ToString())
   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

備註

這個方法會使用 .NET Framework 的複合格式功能,將物件的值轉換成它的文字表示,並在目前StringBuilder的物件中內嵌該標記法。This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.

format參數包含零個或多個與零或多個索引預留位置(稱為格式專案)混合的文字,其對應于此方法的參數清單中的物件。The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to objects in the parameter list of this method. 格式化程式會將每個格式專案取代為對應物件的字串表示。The formatting process replaces each format item with the string representation of the corresponding object.

格式專案的語法如下:The syntax of a format item is as follows:

{index[,length] [:格式字串]}{index[,length][:formatString]}

在方括號中的元素是選擇性的元素。Elements in square brackets are optional. 下表說明每個元素。The following table describes each element.

元素Element 說明Description
indexindex 要格式化之物件的參數清單中以零為起始的位置。The zero-based position in the parameter list of the object to be formatted. 如果index所指定的物件是null,則會將格式String.Empty專案取代為。If the object specified by index is null, the format item is replaced by String.Empty. 如果索引位置中沒有參數, FormatException則會擲回。If there is no parameter in the index position, a FormatException is thrown.
length,length 參數的字串表示中的最小字元數。The minimum number of characters in the string representation of the parameter. 如果是正數,則參數會靠右對齊;如果是負數,則會靠左對齊。If positive, the parameter is right-aligned; if negative, it is left-aligned.
:formatString:formatString 參數所支援的標準或自訂格式字串。A standard or custom format string that is supported by the parameter.

注意

如需搭配日期和時間值使用的標準和自訂格式字串,請參閱標準日期和時間格式字串自訂日期和時間格式字串For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如需搭配數值使用的標準和自訂格式字串,請參閱標準數值格式字串自訂數值格式字串For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. 如需搭配列舉使用的標準格式字串,請參閱列舉格式字串For the standard format strings used with enumerations, see Enumeration Format Strings.

參數會指定可提供和arg0 arg1格式資訊的執行。IFormatProvider providerThe provider parameter specifies an IFormatProvider implementation that can provide formatting information for arg0 and arg1. provider 可以是下列任何項目:provider can be any of the following:

  • CultureInfo物件,提供特定文化特性格式資訊。A CultureInfo object that provides culture-specific formatting information.

  • 物件, arg0 提供arg1的特定文化特性格式資訊,如果是數值,則為。 NumberFormatInfoA NumberFormatInfo object that provides culture-specific formatting information for arg0 or arg1 if they are numeric values.

  • 物件,提供或arg0 arg1的特定文化特性格式資訊,如果它們是日期和時間值,則為。 DateTimeFormatInfoA DateTimeFormatInfo object that provides culture-specific formatting information for arg0 or arg1 if they are date and time values.

  • 提供arg0IFormatProvider 格式arg1資訊的自訂執行。A custom IFormatProvider implementation that provides formatting information for arg0 and arg1. 一般來說,這類的實作為也ICustomFormatter會執行介面。Typically, such an implementation also implements the ICustomFormatter interface.

如果參數為null,則會從目前的文化特性取得格式提供者資訊。 providerIf the provider parameter is null, format provider information is obtained from the current culture.

arg0arg1代表要格式化的物件。arg0 and arg1 represent the objects to be formatted. format的每個格式專案都會取代為具有對應索引之物件的字串表示。Each format item in format is replaced with the string representation of the object that has the corresponding index. 如果格式專案包含formatString ,且對應的引數IFormattable會執行介面,則引數ToString(formatString, provider)的方法會定義格式。If the format item includes formatString and the corresponding argument implements the IFormattable interface, then the argument's ToString(formatString, provider) method defines the formatting. 否則,引數的ToString()方法會定義格式。Otherwise, the argument's ToString() method defines the formatting.

給呼叫者的注意事項

在 .net Core 和在 .NET Framework 4.0 和更新版本中,當您藉由StringBuilder呼叫此StringBuilder(Int32, Int32)函式來具現化物件時, StringBuilder實例的長度和容量都可以成長超過其MaxCapacity的值property.IIn .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. 當您呼叫Append(String)AppendFormat(String, Object)方法來附加小型字串時,可能會發生這種情況。This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

另請參閱

AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object)

將處理複合格式字串所傳回的字串 (其中包含零或更多的格式項目) 附加至這個執行個體。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每一個格式項目都會取代為三個引數中任一個的字串表示。Each format item is replaced by the string representation of either of three arguments.

public:
 System::Text::StringBuilder ^ AppendFormat(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public System.Text.StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2);
member this.AppendFormat : string * obj * obj * obj -> System.Text.StringBuilder
Public Function AppendFormat (format As String, arg0 As Object, arg1 As Object, arg2 As Object) As StringBuilder

參數

format
String String String String

複合格式字串。A composite format 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 的執行個體參考。A reference to this instance with format appended. format 中的每一個格式項目會由對應之物件引數的字串表示所取代。Each format item in format is replaced by the string representation of the corresponding object argument.

例外狀況

format 無效。format is invalid.

-或--or- 格式項目的索引小於 0 (零) 或大於等於 3。The index of a format item is less than 0 (zero), or greater than or equal to 3.

展開後的字串長度會超過 MaxCapacityThe length of the expanded string would exceed MaxCapacity.

範例

下列範例示範AppendFormat方法。The following example demonstrates the AppendFormat method.

using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
   Console::WriteLine( sbs );
   sbs->Length = 0;
}

int main()
{
   StringBuilder^ sb = gcnew StringBuilder;
   int var1 = 111;
   float var2 = 2.22F;
   String^ var3 = "abcd";
   array<Object^>^var4 = {3,4.4,(Char)'X'};
   Console::WriteLine();
   Console::WriteLine( "StringBuilder.AppendFormat method:" );
   sb->AppendFormat( "1) {0}", var1 );
   Show( sb );
   sb->AppendFormat( "2) {0}, {1}", var1, var2 );
   Show( sb );
   sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
   Show( sb );
   sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
   Show( sb );
   CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
   array<Object^>^temp1 = {var2};
   sb->AppendFormat( ci, "5) {0}", temp1 );
   Show( sb );
}

/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;

class Sample 
{
    static StringBuilder sb = new StringBuilder();

    public static void Main() 
    {
    int    var1   = 111;
    float  var2   = 2.22F;
    string var3   = "abcd";
    object[] var4 = {3, 4.4, 'X'};

    Console.WriteLine();
    Console.WriteLine("StringBuilder.AppendFormat method:");
    sb.AppendFormat("1) {0}", var1);
    Show(sb);
    sb.AppendFormat("2) {0}, {1}", var1, var2);
    Show(sb);
    sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
    Show(sb);
    sb.AppendFormat("4) {0}, {1}, {2}", var4);
    Show(sb);
    CultureInfo ci = new CultureInfo("es-ES", true);
    sb.AppendFormat(ci, "5) {0}", var2);
    Show(sb);
    }

    public static void Show(StringBuilder sbs)
    {
    Console.WriteLine(sbs.ToString());
    sb.Length = 0;
    }
}
/*
This example produces the following results:

StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization

Class Sample
   Private Shared sb As New StringBuilder()

   Public Shared Sub Main()
      Dim var1 As Integer = 111
      Dim var2 As Single = 2.22F
      Dim var3 As String = "abcd"
      Dim var4 As Object() =  {3, 4.4, "X"c}
      
      Console.WriteLine()
      Console.WriteLine("StringBuilder.AppendFormat method:")
      sb.AppendFormat("1) {0}", var1)
      Show(sb)
      sb.AppendFormat("2) {0}, {1}", var1, var2)
      Show(sb)
      sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
      Show(sb)
      sb.AppendFormat("4) {0}, {1}, {2}", var4)
      Show(sb)
      Dim ci As New CultureInfo("es-ES", True)
      sb.AppendFormat(ci, "5) {0}", var2)
      Show(sb)
   End Sub
   
   Public Shared Sub Show(sbs As StringBuilder)
      Console.WriteLine(sbs.ToString())
      sb.Length = 0
   End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22

備註

這個方法會使用 .NET Framework 的複合格式功能,將物件的值轉換成它的文字表示,並在目前StringBuilder的物件中內嵌該標記法。This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.

參數包含零個或多個與零或多個索引預留位置(稱為格式專案)混合的文字,此方法的arg2參數清單中的物件會對應至arg0formatThe format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to arg0 through arg2, the objects in the parameter list of this method. 格式化程式會將每個格式專案取代為對應物件的字串表示。The formatting process replaces each format item with the string representation of the corresponding object.

格式專案的語法如下:The syntax of a format item is as follows:

{index[,length] [:格式字串]}{index[,length][:formatString]}

在方括號中的元素是選擇性的元素。Elements in square brackets are optional. 下表說明每個元素。The following table describes each element.

元素Element 說明Description
indexindex 要格式化之物件的參數清單中以零為起始的位置。The zero-based position in the parameter list of the object to be formatted. 如果index所指定的物件是null,則會將格式String.Empty專案取代為。If the object specified by index is null, the format item is replaced by String.Empty. 如果索引位置中沒有參數, FormatException則會擲回。If there is no parameter in the index position, a FormatException is thrown.
length,length 參數的字串表示中的最小字元數。The minimum number of characters in the string representation of the parameter. 如果是正數,則參數會靠右對齊;如果是負數,則會靠左對齊。If positive, the parameter is right-aligned; if negative, it is left-aligned.
:formatString:formatString 參數所支援的標準或自訂格式字串。A standard or custom format string that is supported by the parameter.

注意

如需搭配日期和時間值使用的標準和自訂格式字串,請參閱標準日期和時間格式字串自訂日期和時間格式字串For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. 如需搭配數值使用的標準和自訂格式字串,請參閱標準數值格式字串自訂數值格式字串For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. 如需搭配列舉使用的標準格式字串,請參閱列舉格式字串For the standard format strings used with enumerations, see Enumeration Format Strings.

arg0arg1arg2代表要格式化的物件。arg0, arg1, and arg2 represent the objects to be formatted. format的每個格式專案都會取代為arg0arg1arg2的字串表示(視格式專案的索引而定)。Each format item in format is replaced with the string representation of either arg0, arg1, or arg2, depending on the index of the format item. 如果格式專案包含formatString ,且中.ToString(formatString, null) IFormattable args的對應物件會執行介面,則arg x會定義格式,其中x是引數的索引。If the format item includes formatString and the corresponding object in args implements the IFormattable interface, then argx.ToString(formatString, null) defines the formatting, where x is the index of the argument. 否則, arg x.ToString()會定義格式。Otherwise, argx.ToString() defines the formatting.

如果指派給format的字串是「感謝您將 {0: # # # #} 的食物捐贈給我們的慈善組織。」If the string assigned to format is "Thank you for your donation of {0:####} cans of food to our charitable organization." arg0是值為10的整數,傳回值將會是「感謝您捐贈10罐的食物給我們的慈善組織。」and arg0 is an integer with the value 10, the return value will be "Thank you for your donation of 10 cans of food to our charitable organization."

給呼叫者的注意事項

在 .net Core 和 .NET Framework 4.0 和更新版本中,當您藉由呼叫StringBuilderStringBuilder(Int32, Int32)函式來具現化物件時, StringBuilder實例的長度和容量都可以成長超過其MaxCapacity的值property.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. 當您呼叫Append(String)AppendFormat(String, Object)方法來附加小型字串時,可能會發生這種情況。This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

另請參閱

適用於