在 .NET 中將類型格式化Formatting Types in .NET

格式化是將類別、結構或列舉值的執行個體轉換成字串表示的過程,通常是為了將結果字串展示予使用者,或是為了將字串藉還原序列化方式還原成原始的資料類型。Formatting is the process of converting an instance of a class, structure, or enumeration value to its string representation, often so that the resulting string can be displayed to users or deserialized to restore the original data type. 這種轉換可能面臨幾項挑戰:This conversion can pose a number of challenges:

  • 值的內部儲存方式不見得反映出使用者想要的檢視方式。The way that values are stored internally does not necessarily reflect the way that users want to view them. 例如,電話號碼可能以 8009999999 的格式儲存,但這並不太符合使用者的閱讀習慣。For example, a telephone number might be stored in the form 8009999999, which is not user-friendly. 應該改以顯示成 800-999-9999。It should instead be displayed as 800-999-9999. 如需以此方式格式化數字的範例,請參閱 自訂格式字串 一節。See the Custom Format Strings section for an example that formats a number in this way.

  • 物件轉換後的字串表示有時候並不符合直覺。Sometimes the conversion of an object to its string representation is not intuitive. 例如,Temperature 物件或 Person 物件的字串表示應該為何種格式,就不是那麼清楚。For example, it is not clear how the string representation of a Temperature object or a Person object should appear. 如需以各種方式將 Temperature 物件格式化的範例,請參閱 標準格式字串 一節。For an example that formats a Temperature object in a variety of ways, see the Standard Format Strings section.

  • 值的格式通常需要符合文化特性。Values often require culture-sensitive formatting. 例如,如果應用程式需要使用數字來表達貨幣值,則數值字串應該包含目前文化特性的貨幣符號、群組分隔符號 (即大部分文化特性中的千位分隔符號) 和小數點符號。For example, in an application that uses numbers to reflect monetary values, numeric strings should include the current culture’s currency symbol, group separator (which, in most cultures, is the thousands separator), and decimal symbol. 如需範例,請參閱 以格式提供者和 IFormatProvider 介面進行符合文化特性的格式化 一節。For an example, see the Culture-Sensitive Formatting with Format Providers and the IFormatProvider Interface section.

  • 應用程式可能需要以不同的方式來顯示相同的值。An application may have to display the same value in different ways. 例如,應用程式在表示列舉成員時,在做法上可能是顯示其名稱的字串表示,或顯示其基礎值。For example, an application may represent an enumeration member by displaying a string representation of its name or by displaying its underlying value. 如需以不同方式格式化 DayOfWeek 列舉成員的範例,請參閱 標準格式字串 一節。For an example that formats a member of the DayOfWeek enumeration in different ways, see the Standard Format Strings section.

注意

格式化會將某種類型的值轉換為字串表示。Formatting converts the value of a type into a string representation. 剖析是格式化的反向操作。Parsing is the inverse of formatting. 剖析作業會從資料類型的字串表示來建立資料類型的執行個體。A parsing operation creates an instance of a data type from its string representation. 如需將字串轉換為其他資料類型的相關資訊,請參閱 Parsing StringsFor information about converting strings to other data types, see Parsing Strings.

.NET 提供豐富的格式化支援,可滿足開發人員的這些需求。.NET provides rich formatting support that enables developers to address these requirements.

本概觀包含下列各節:This overview contains the following sections:

.NET 中的格式化​​Formatting in .NET

格式化機制的基礎在於 Object.ToString 方法的預設實作,這將於本主題稍後的使用 ToString 方法的預設格式一節中討論。The basic mechanism for formatting is the default implementation of the Object.ToString method, which is discussed in the Default Formatting Using the ToString Method section later in this topic. 不過,.NET 提供幾種方式來修改和擴充其預設格式化支援。However, .NET provides several ways to modify and extend its default formatting support. 這些需求包括下列各項:These include the following:

  • 覆寫 Object.ToString 方法來自訂物件值的字串表示。Overriding the Object.ToString method to define a custom string representation of an object’s value. 如需詳細資訊,請參閱本主題稍後的 覆寫 ToString 方法 一節。For more information, see the Overriding the ToString Method section later in this topic.

  • 定義格式規範,格式規範讓物件值的字串表示可以採用多種形式。Defining format specifiers that enable the string representation of an object’s value to take multiple forms. 例如,下列陳述式中的 "X" 格式規範會將整數轉換為十六進位值的字串表示。For example, the "X" format specifier in the following statement converts an integer to the string representation of a hexadecimal value.

    int integerValue = 60312;
    Console.WriteLine(integerValue.ToString("X"));   // Displays EB98.
    
    Dim integerValue As Integer = 60312
    Console.WriteLine(integerValue.ToString("X"))   ' Displays EB98.
    

    如需格式規範的詳細資訊,請參閱 ToString 方法和格式字串 一節。For more information about format specifiers, see the ToString Method and Format Strings section.

  • 透過格式提供者來採用特定文化特性的格式化慣例。Using format providers to take advantage of the formatting conventions of a specific culture. 例如,下列陳述式會使用 en-US 文化特性的格式化慣例來顯示貨幣值。For example, the following statement displays a currency value by using the formatting conventions of the en-US culture.

    double cost = 1632.54; 
    Console.WriteLine(cost.ToString("C", 
                      new System.Globalization.CultureInfo("en-US")));   
    // The example displays the following output:
    //       $1,632.54
    
    Dim cost As Double = 1632.54
    Console.WriteLine(cost.ToString("C", New System.Globalization.CultureInfo("en-US")))
    ' The example displays the following output:
    '       $1,632.54
    

    如需以格式提供者進行格式化的詳細資訊,請參閱 格式提供者和 IFormatProvider 介面 一節。For more information about formatting with format providers, see the Format Providers and the IFormatProvider Interface section.

  • 實作 IFormattable 介面,以同時支援使用 Convert 類別和複合格式來轉換字串。Implementing the IFormattable interface to support both string conversion with the Convert class and composite formatting. 如需詳細資訊,請參閱 IFormattable 介面 一節。For more information, see the IFormattable Interface section.

  • 使用複合格式將值的字串表示嵌入更大的字串中。Using composite formatting to embed the string representation of a value in a larger string. 如需詳細資訊,請參閱 複合格式 一節。For more information, see the Composite Formatting section.

  • 實作 ICustomFormatterIFormatProvider 來提供完整的自訂格式解決方案。Implementing ICustomFormatter and IFormatProvider to provide a complete custom formatting solution. 如需詳細資訊,請參閱 使用 ICustomFormatter 的自訂格式 一節。For more information, see the Custom Formatting with ICustomFormatter section.

下列各節會討論這些將物件轉換為其字串表示的方法。The following sections examine these methods for converting an object to its string representation.

使用 ToString 方法的預設格式Default Formatting Using the ToString Method

每個衍生自 System.Object 的類型都會自動繼承無參數的 ToString 方法,這個方法預設會傳回類型的名稱。Every type that is derived from System.Object automatically inherits a parameterless ToString method, which returns the name of the type by default. 下列範例示範預設的 ToString 方法。The following example illustrates the default ToString method. 範例中會定義一個不具任何實作的 Automobile 類別。It defines a class named Automobile that has no implementation. 當具現化這個類別並呼叫其 ToString 方法時,會顯示這個類別的類型名稱。When the class is instantiated and its ToString method is called, it displays its type name. 請注意,在範例中不會明確呼叫 ToString 方法。Note that the ToString method is not explicitly called in the example. Console.WriteLine(Object) 方法會隱含呼叫本身所收到做為引數傳遞之物件的 ToString 方法。The Console.WriteLine(Object) method implicitly calls the ToString method of the object passed to it as an argument.

using System;

public class Automobile
{
   // No implementation. All members are inherited from Object.
}

public class Example
{
   public static void Main()
   {
      Automobile firstAuto = new Automobile();
      Console.WriteLine(firstAuto);
   }
}
// The example displays the following output:
//       Automobile
Public Class Automobile
   ' No implementation. All members are inherited from Object.
End Class

Module Example
   Public Sub Main()
      Dim firstAuto As New Automobile()
      Console.WriteLine(firstAuto)
   End Sub
End Module
' The example displays the following output:
'       Automobile

警告

Windows 8.1Windows 8.1 起,Windows 執行階段即包含了 IStringable 介面。此介面只有一個方法 IStringable.ToString,可提供預設的格式化支援。Starting with Windows 8.1Windows 8.1, the Windows Runtime includes an IStringable interface with a single method, IStringable.ToString, which provides default formatting support. 不過,不建議 Managed 類型實作 IStringable 介面。However, we recommend that managed types do not implement the IStringable interface. 如需詳細資訊,請參閱 Object.ToString 參考頁面中的<Windows 執行階段與 IStringable 介面>>一節。For more information, see "The Windows Runtime and the IStringable Interface" section on the Object.ToString reference page.

因為除介面以外的所有其他類型都會衍生自 Object,所以您的自訂類別或結構會自動被賦予此功能。Because all types other than interfaces are derived from Object, this functionality is automatically provided to your custom classes or structures. 不過,預設 ToString 方法所提供的功能會受到限制:雖然其可以識別類型,但無法提供類型之執行個體的任何資訊。However, the functionality offered by the default ToString method, is limited: Although it identifies the type, it fails to provide any information about an instance of the type. 若要提供物件的字串表示來表達該物件的相關資訊,您必須覆寫 ToString 方法。To provide a string representation of an object that provides information about that object, you must override the ToString method.

注意

結構會繼承自 ValueType,而後者又會衍生自 ObjectStructures inherit from ValueType, which in turn is derived from Object. 雖然 ValueType 會覆寫 Object.ToString,但實作方法是相同的。Although ValueType overrides Object.ToString, its implementation is identical.

覆寫 ToString 方法Overriding the ToString Method

顯示類型的名稱通常用途不大,亦無法讓您類型的使用者藉以區分不同的執行個體。Displaying the name of a type is often of limited use and does not allow consumers of your types to differentiate one instance from another. 不過,您可以覆寫 ToString 方法,以更實用的方式表示物件的值。However, you can override the ToString method to provide a more useful representation of an object’s value. 下列範例定義 Temperature 物件,並覆寫其 ToString 方法來顯示攝氏溫度。The following example defines a Temperature object and overrides its ToString method to display the temperature in degrees Celsius.

using System;

public class Temperature
{
   private decimal temp;
   
   public Temperature(decimal temperature)
   {
      this.temp = temperature;   
   }

   public override string ToString()
   {
      return this.temp.ToString("N1") + "°C";
   }
}

public class Example
{
   public static void Main()
   {
      Temperature currentTemperature = new Temperature(23.6m);
      Console.WriteLine("The current temperature is " +
                        currentTemperature.ToString());
   }
}
// The example displays the following output:
//       The current temperature is 23.6°C.
Public Class Temperature
   Private temp As Decimal
   
   Public Sub New(temperature As Decimal)
      Me.temp = temperature
   End Sub
   
   Public Overrides Function ToString() As String
      Return Me.temp.ToString("N1") + "°C"   
   End Function
End Class

Module Example
   Public Sub Main()
      Dim currentTemperature As New Temperature(23.6d)
      Console.WriteLine("The current temperature is " +
                        currentTemperature.ToString())
   End Sub
End Module
' The example displays the following output:
'       The current temperature is 23.6°C.

在 .NET 中,已覆寫每個基本實值類型的 ToString 方法來顯示物件的值,而非物件的名稱。In .NET, the ToString method of each primitive value type has been overridden to display the object’s value instead of its name. 下表顯示各基本類型如何覆寫 ToString 方法。The following table shows the override for each primitive type. 請注意,大部分經過覆寫的方法都會呼叫 ToString 方法的另一個多載,並且將 "G" 格式規範 (此規範定義此類型的一般格式) 和 IFormatProvider 物件 (此物件表示目前文化特性) 傳遞至這個多載。Note that most of the overridden methods call another overload of the ToString method and pass it the "G" format specifier, which defines the general format for its type, and an IFormatProvider object that represents the current culture.

類型Type ToString 覆寫ToString override
Boolean 傳回 Boolean.TrueStringBoolean.FalseStringReturns either Boolean.TrueString or Boolean.FalseString.
Byte 呼叫 Byte.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 Byte 值。Calls Byte.ToString("G", NumberFormatInfo.CurrentInfo) to format the Byte value for the current culture.
Char 以字串形式傳回字元。Returns the character as a string.
DateTime 呼叫 DateTime.ToString("G", DatetimeFormatInfo.CurrentInfo) ,以根據對目前的文化特性來格式化日期和時間值。Calls DateTime.ToString("G", DatetimeFormatInfo.CurrentInfo) to format the date and time value for the current culture.
Decimal 呼叫 Decimal.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 Decimal 值。Calls Decimal.ToString("G", NumberFormatInfo.CurrentInfo) to format the Decimal value for the current culture.
Double 呼叫 Double.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 Double 值。Calls Double.ToString("G", NumberFormatInfo.CurrentInfo) to format the Double value for the current culture.
Int16 呼叫 Int16.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 Int16 值。Calls Int16.ToString("G", NumberFormatInfo.CurrentInfo) to format the Int16 value for the current culture.
Int32 呼叫 Int32.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 Int32 值。Calls Int32.ToString("G", NumberFormatInfo.CurrentInfo) to format the Int32 value for the current culture.
Int64 呼叫 Int64.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 Int64 值。Calls Int64.ToString("G", NumberFormatInfo.CurrentInfo) to format the Int64 value for the current culture.
SByte 呼叫 SByte.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 SByte 值。Calls SByte.ToString("G", NumberFormatInfo.CurrentInfo) to format the SByte value for the current culture.
Single 呼叫 Single.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 Single 值。Calls Single.ToString("G", NumberFormatInfo.CurrentInfo) to format the Single value for the current culture.
UInt16 呼叫 UInt16.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 UInt16 值。Calls UInt16.ToString("G", NumberFormatInfo.CurrentInfo) to format the UInt16 value for the current culture.
UInt32 呼叫 UInt32.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 UInt32 值。Calls UInt32.ToString("G", NumberFormatInfo.CurrentInfo) to format the UInt32 value for the current culture.
UInt64 呼叫 UInt64.ToString("G", NumberFormatInfo.CurrentInfo) ,以根據目前的文化特性來格式化 UInt64 值。Calls UInt64.ToString("G", NumberFormatInfo.CurrentInfo) to format the UInt64 value for the current culture.

ToString 方法和格式字串The ToString Method and Format Strings

當物件只有單一字串表示時,使用預設 ToString 方法或覆寫 ToString 都沒有問題。Relying on the default ToString method or overriding ToString is appropriate when an object has a single string representation. 不過,物件的值通常有多種表示。However, the value of an object often has multiple representations. 例如,溫度可以用華氏、攝氏或開氏溫度表示。For example, a temperature can be expressed in degrees Fahrenheit, degrees Celsius, or kelvins. 同樣地,整數值 10 可以用許多方式表示,包括 10、10.0、1.0e01 或 $10.00。Similarly, the integer value 10 can be represented in numerous ways, including 10, 10.0, 1.0e01, or $10.00.

為了讓單一值可以具有多種字串表示,.NET 使用格式字串。To enable a single value to have multiple string representations, .NET uses format strings. 格式字串是包含一個或多個預先定義之格式規範的字串,這個字串是單一字元或一組字元,用於定義 ToString 方法應採用的輸出格式。A format string is a string that contains one or more predefined format specifiers, which are single characters or groups of characters that define how the ToString method should format its output. 然後,格式字串會當做參數傳遞至物件的 ToString 方法,以決定如何呈現該物件的值的字串表示。The format string is then passed as a parameter to the object's ToString method and determines how the string representation of that object's value should appear.

.NET 中所有的數值類型、日期和時間類型,以及列舉類型,都支援一組預先定義的格式規範。All numeric types, date and time types, and enumeration types in .NET support a predefined set of format specifiers. 您也可以利用格式字串定義多種字串表示給您應用程式中定義的資料類型。You can also use format strings to define multiple string representations of your application-defined data types.

標準格式字串Standard Format Strings

標準格式字串包含單一格式規範 (一個字母字元,定義套用此規範之物件的字串表示) 和選擇性的精確度規範 (這個規範影響結果字串中顯示的位數)。A standard format string contains a single format specifier, which is an alphabetic character that defines the string representation of the object to which it is applied, along with an optional precision specifier that affects how many digits are displayed in the result string. 如果省略或不支援精確度規範,則標準格式規範與標準格式字串無異。If the precision specifier is omitted or is not supported, a standard format specifier is equivalent to a standard format string.

.NET 定義一組適用於所有數值類型、所有日期和時間類型,以及所有列舉類型的標準格式規範。.NET defines a set of standard format specifiers for all numeric types, all date and time types, and all enumeration types. 例如,這些分類每個都支援 "G" 標準格式規範 (這個規範定義該類型之值的一般字串表示)。For example, each of these categories supports a "G" standard format specifier, which defines a general string representation of a value of that type.

列舉類型的標準格式字串直接控制了值的字串表示。Standard format strings for enumeration types directly control the string representation of a value. 傳遞給列舉值的 ToString 方法的格式字串決定了該值是以其字串名稱 ("G" 和 "F" 格式規範)、基礎整數值 ("D" 格式規範),還是十六進位值 ("X" 格式規範) 來顯示。The format strings passed to an enumeration value’s ToString method determine whether the value is displayed using its string name (the "G" and "F" format specifiers), its underlying integral value (the "D" format specifier), or its hexadecimal value (the "X" format specifier). 下列範例示範如何使用標準格式字串來格式化 DayOfWeek 列舉值。The following example illustrates the use of standard format strings to format a DayOfWeek enumeration value.

DayOfWeek thisDay = DayOfWeek.Monday;
string[] formatStrings = {"G", "F", "D", "X"};

foreach (string formatString in formatStrings)
   Console.WriteLine(thisDay.ToString(formatString));
// The example displays the following output:
//       Monday
//       Monday
//       1
//       00000001
Dim thisDay As DayOfWeek = DayOfWeek.Monday
Dim formatStrings() As String = {"G", "F", "D", "X"}

For Each formatString As String In formatStrings
   Console.WriteLine(thisDay.ToString(formatString))
Next
' The example displays the following output:
'       Monday
'       Monday
'       1
'       00000001

如需列舉格式字串的相關資訊,請參閱 Enumeration Format StringsFor information about enumeration format strings, see Enumeration Format Strings.

數值類型的標準格式字串定義出的結果字串之確切外觀通常是由一個或多個屬性值所控制。Standard format strings for numeric types usually define a result string whose precise appearance is controlled by one or more property values. 例如,"C" 格式規範會將數字格式化為貨幣值。For example, the "C" format specifier formats a number as a currency value. 當您將 "C" 格式規範做為唯一參數來呼叫 ToString 方法時,會使用目前文化特性之 NumberFormatInfo 物件中的下列屬性值來定義數值的字串表示:When you call the ToString method with the "C" format specifier as the only parameter, the following property values from the current culture’s NumberFormatInfo object are used to define the string representation of the numeric value:

  • CurrencySymbol 屬性,指定目前文化特性的貨幣符號。The CurrencySymbol property, which specifies the current culture’s currency symbol.

  • CurrencyNegativePatternCurrencyPositivePattern 屬性,這個屬性傳回的整數會決定:The CurrencyNegativePattern or CurrencyPositivePattern property, which returns an integer that determines the following:

    • 貨幣符號的位置。The placement of the currency symbol.

    • 負值是以開頭負號、結尾負號還是括號來表示。Whether negative values are indicated by a leading negative sign, a trailing negative sign, or parentheses.

    • 數值和貨幣符號之間是否顯示一個空格。Whether a space appears between the numeric value and the currency symbol.

  • CurrencyDecimalDigits 屬性,定義結果字串中的小數位數。The CurrencyDecimalDigits property, which defines the number of fractional digits in the result string.

  • CurrencyDecimalSeparator 屬性,定義結果字串中的十進位分隔符號。The CurrencyDecimalSeparator property, which defines the decimal separator symbol in the result string.

  • CurrencyGroupSeparator 屬性,定義群組分隔符號。The CurrencyGroupSeparator property, which defines the group separator symbol.

  • CurrencyGroupSizes 屬性,定義小數點左邊每個群組的位數。The CurrencyGroupSizes property, which defines the number of digits in each group to the left of the decimal.

  • NegativeSign 屬性,決定當不使用括號來表示負數時,要在結果字串中使用的負數值表示符號。The NegativeSign property, which determines the negative sign used in the result string if parentheses are not used to indicate negative values.

此外,數值格式字串也可以包含精確度規範。In addition, numeric format strings may include a precision specifier. 這個規範的意義視搭配使用的格式字串而定,但通常是表示結果字串中應該顯示的總位數或小數位數。The meaning of this specifier depends on the format string with which it is used, but it typically indicates either the total number of digits or the number of fractional digits that should appear in the result string. 例如,下列範例會使用 "X4" 標準數值字串和精確度規範,建立具有四個十六進位數字的字串值。For example, the following example uses the "X4" standard numeric string and a precision specifier to create a string value that has four hexadecimal digits.

byte[] byteValues = { 12, 163, 255 };
foreach (byte byteValue in byteValues)
   Console.WriteLine(byteValue.ToString("X4"));
// The example displays the following output:
//       000C
//       00A3
//       00FF
Dim byteValues() As Byte = { 12, 163, 255 }
For Each byteValue As Byte In byteValues
   Console.WriteLine(byteValue.ToString("X4"))
Next
' The example displays the following output:
'       000C
'       00A3
'       00FF

如需標準數值格式字串的詳細資訊,請參閱 Standard Numeric Format StringsFor more information about standard numeric formatting strings, see Standard Numeric Format Strings.

日期和時間值的標準格式字串是特定 DateTimeFormatInfo 屬性所儲存之自訂格式字串的別名。Standard format strings for date and time values are aliases for custom format strings stored by a particular DateTimeFormatInfo property. 例如,以 "D" 格式規範來呼叫日期和時間值的 ToString 方法,將會使用目前文化特性之 DateTimeFormatInfo.LongDatePattern 屬性中所儲存的自訂格式字串來顯示日期和時間For example, calling the ToString method of a date and time value with the "D" format specifier displays the date and time by using the custom format string stored in the current culture’s DateTimeFormatInfo.LongDatePattern property. (如需自訂格式字串的詳細資訊,請參閱下一節)。下列範例示範這種關聯性。(For more information about custom format strings, see the next section.) The following example illustrates this relationship.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2009, 6, 30);
      Console.WriteLine("D Format Specifier:     {0:D}", date1);
      string longPattern = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern;
      Console.WriteLine("'{0}' custom format string:     {1}", 
                        longPattern, date1.ToString(longPattern));
   }
}
// The example displays the following output when run on a system whose
// current culture is en-US:
//    D Format Specifier:     Tuesday, June 30, 2009
//    'dddd, MMMM dd, yyyy' custom format string:     Tuesday, June 30, 2009
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim date1 As Date = #6/30/2009#
      Console.WriteLine("D Format Specifier:     {0:D}", date1)
      Dim longPattern As String = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern
      Console.WriteLine("'{0}' custom format string:     {1}", _
                        longPattern, date1.ToString(longPattern))
   End Sub
End Module
' The example displays the following output when run on a system whose
' current culture is en-US:
'    D Format Specifier:     Tuesday, June 30, 2009
'    'dddd, MMMM dd, yyyy' custom format string:     Tuesday, June 30, 2009

如需標準日期和時間格式字串的詳細資訊,請參閱 Standard Date and Time Format StringsFor more information about standard date and time format strings, see Standard Date and Time Format Strings.

對於應用程式定義的物件,您也可以使用標準格式字串來定義由該物件的 ToString(String) 方法所產生的字串表示。You can also use standard format strings to define the string representation of an application-defined object that is produced by the object’s ToString(String) method. 您可以定義您的物件所支援的特定標準格式規範,並且決定這項規範是否區分大小寫。You can define the specific standard format specifiers that your object supports, and you can determine whether they are case-sensitive or case-insensitive. 您對 ToString(String) 方法的實作應該要能支援:Your implementation of the ToString(String) method should support the following:

  • "G" 格式規範,表示物件的慣用或通用格式。A "G" format specifier that represents a customary or common format of the object. 您物件的 ToString 方法的無參數多載應該要呼叫這個方法的 ToString(String) 多載,並且將 "G" 標準格式字串傳遞給這個方法。The parameterless overload of your object's ToString method should call its ToString(String) overload and pass it the "G" standard format string.

  • 支援等於 null 參考 (在 Visual Basic 中為Nothing ) 的格式規範。Support for a format specifier that is equal to a null reference (Nothing in Visual Basic). 等於 null 參考的格式規範應該要視為相當於 "G" 格式規範。A format specifier that is equal to a null reference should be considered equivalent to the "G" format specifier.

例如, Temperature 類別可以在內部以攝氏儲存溫度,並透過格式規範以攝氏、華氏和開氏溫度來表示 Temperature 物件的值。For example, a Temperature class can internally store the temperature in degrees Celsius and use format specifiers to represent the value of the Temperature object in degrees Celsius, degrees Fahrenheit, and kelvins. 下列範例提供一個實例。The following example provides an illustration.

using System;

public class Temperature
{
   private decimal m_Temp;
   
   public Temperature(decimal temperature)
   {
      this.m_Temp = temperature;
   }
   
   public decimal Celsius
   {
      get { return this.m_Temp; }
   }
   
   public decimal Kelvin
   {
      get { return this.m_Temp + 273.15m; }   
   }
   
   public decimal Fahrenheit
   {
      get { return Math.Round(((decimal) (this.m_Temp * 9 / 5 + 32)), 2); }
   }

   public override string ToString()
   {
      return this.ToString("C");
   }
   
   public string ToString(string format)
   {  
      // Handle null or empty string.
      if (String.IsNullOrEmpty(format)) format = "C";
      // Remove spaces and convert to uppercase.
      format = format.Trim().ToUpperInvariant();      
      
      // Convert temperature to Fahrenheit and return string.
      switch (format)
      {
         // Convert temperature to Fahrenheit and return string.
         case "F":
            return this.Fahrenheit.ToString("N2") + " °F";
         // Convert temperature to Kelvin and return string.
         case "K":
            return this.Kelvin.ToString("N2") + " K";
         // return temperature in Celsius.
         case "G":
         case "C":
            return this.Celsius.ToString("N2") + " °C";
         default:
            throw new FormatException(String.Format("The '{0}' format string is not supported.", format));
      }      
   }
}

public class Example
{
   public static void Main()
   {
      Temperature temp1 = new Temperature(0m);
      Console.WriteLine(temp1.ToString());
      Console.WriteLine(temp1.ToString("G"));
      Console.WriteLine(temp1.ToString("C"));
      Console.WriteLine(temp1.ToString("F"));
      Console.WriteLine(temp1.ToString("K"));

      Temperature temp2 = new Temperature(-40m);
      Console.WriteLine(temp2.ToString());
      Console.WriteLine(temp2.ToString("G"));
      Console.WriteLine(temp2.ToString("C"));
      Console.WriteLine(temp2.ToString("F"));
      Console.WriteLine(temp2.ToString("K"));

      Temperature temp3 = new Temperature(16m);
      Console.WriteLine(temp3.ToString());
      Console.WriteLine(temp3.ToString("G"));
      Console.WriteLine(temp3.ToString("C"));
      Console.WriteLine(temp3.ToString("F"));
      Console.WriteLine(temp3.ToString("K"));
      
      Console.WriteLine(String.Format("The temperature is now {0:F}.", temp3));
   }
}
// The example displays the following output:
//       0.00 °C
//       0.00 °C
//       0.00 °C
//       32.00 °F
//       273.15 K
//       -40.00 °C
//       -40.00 °C
//       -40.00 °C
//       -40.00 °F
//       233.15 K
//       16.00 °C
//       16.00 °C
//       16.00 °C
//       60.80 °F
//       289.15 K
//       The temperature is now 16.00 °C.
Public Class Temperature
   Private m_Temp As Decimal
   
   Public Sub New(temperature As Decimal)
      Me.m_Temp = temperature
   End Sub
   
   Public ReadOnly Property Celsius() As Decimal
      Get
         Return Me.m_Temp
      End Get   
   End Property
   
   Public ReadOnly Property Kelvin() As Decimal
      Get
         Return Me.m_Temp + 273.15d   
      End Get
   End Property
   
   Public ReadOnly Property Fahrenheit() As Decimal
      Get
         Return Math.Round(CDec(Me.m_Temp * 9 / 5 + 32), 2)
      End Get      
   End Property

   Public Overrides Function ToString() As String
      Return Me.ToString("C")
   End Function
   
   Public Overloads Function ToString(format As String) As String  
      ' Handle null or empty string.
      If String.IsNullOrEmpty(format) Then format = "C"
      ' Remove spaces and convert to uppercase.
      format = format.Trim().ToUpperInvariant()      
      
      Select Case format
         Case "F"
           ' Convert temperature to Fahrenheit and return string.
            Return Me.Fahrenheit.ToString("N2") & " °F"
         Case "K"
            ' Convert temperature to Kelvin and return string.
            Return Me.Kelvin.ToString("N2") & " K"
         Case "C", "G"
            ' Return temperature in Celsius.
            Return Me.Celsius.ToString("N2") & " °C"
         Case Else
            Throw New FormatException(String.Format("The '{0}' format string is not supported.", format))
      End Select      
   End Function
End Class

Public Module Example
   Public Sub Main()
      Dim temp1 As New Temperature(0d)
      Console.WriteLine(temp1.ToString())
      Console.WriteLine(temp1.ToString("G"))
      Console.WriteLine(temp1.ToString("C"))
      Console.WriteLine(temp1.ToString("F"))
      Console.WriteLine(temp1.ToString("K"))

      Dim temp2 As New Temperature(-40d)
      Console.WriteLine(temp2.ToString())
      Console.WriteLine(temp2.ToString("G"))
      Console.WriteLine(temp2.ToString("C"))
      Console.WriteLine(temp2.ToString("F"))
      Console.WriteLine(temp2.ToString("K"))

      Dim temp3 As New Temperature(16d)
      Console.WriteLine(temp3.ToString())
      Console.WriteLine(temp3.ToString("G"))
      Console.WriteLine(temp3.ToString("C"))
      Console.WriteLine(temp3.ToString("F"))
      Console.WriteLine(temp3.ToString("K"))
      
      Console.WriteLine(String.Format("The temperature is now {0:F}.", temp3))
   End Sub
End Module
' The example displays the following output:
'       0.00 °C
'       0.00 °C
'       0.00 °C
'       32.00 °F
'       273.15 K
'       -40.00 °C
'       -40.00 °C
'       -40.00 °C
'       -40.00 °F
'       233.15 K
'       16.00 °C
'       16.00 °C
'       16.00 °C
'       60.80 °F
'       289.15 K
'       The temperature is now 16.00 °C.

自訂格式字串Custom Format Strings

除了標準格式字串,.NET 也為數值以及日期和時間值定義了自訂格式字串。In addition to the standard format strings, .NET defines custom format strings for both numeric values and date and time values. 自訂格式字串由一個或多個自訂格式規範組成,這些規範定義了值的字串表示。A custom format string consists of one or more custom format specifiers that define the string representation of a value. 例如,自訂日期和時間格式字串 "yyyy/mm/dd hh:mm:ss.ffff t zzz" 會將日期轉換為其字串表示,以 en-US 文化特性而言為 "2008/11/15 07:45:00.0000 P -08:00" 形式。For example, the custom date and time format string "yyyy/mm/dd hh:mm:ss.ffff t zzz" converts a date to its string representation in the form "2008/11/15 07:45:00.0000 P -08:00" for the en-US culture. 同樣地,自訂格式字串 "0000" 會將整數值 12 轉換為 "0012"。Similarly, the custom format string "0000" converts the integer value 12 to "0012". 如需完整的自訂格式字串清單,請參閱 Custom Date and Time Format StringsCustom Numeric Format StringsFor a complete list of custom format strings, see Custom Date and Time Format Strings and Custom Numeric Format Strings.

如果格式字串由單一自訂格式規範組成,則應該在格式規範前面加上百分比 (%) 符號,以避免與標準格式規範產生混淆。If a format string consists of a single custom format specifier, the format specifier should be preceded by the percent (%) symbol to avoid confusion with a standard format specifier. 下列範例會使用 "M" 自訂格式規範來顯示特定日期的一位數或兩位數月份。The following example uses the "M" custom format specifier to display a one-digit or two-digit number of the month of a particular date.

DateTime date1 = new DateTime(2009, 9, 8);
Console.WriteLine(date1.ToString("%M"));       // Displays 9
Dim date1 As Date = #09/08/2009#
Console.WriteLine(date1.ToString("%M"))      ' Displays 9

日期和時間值的許多標準格式字串都是自訂格式字串 (這些自訂格式字串由 DateTimeFormatInfo 物件的屬性所定義) 的別名。Many standard format strings for date and time values are aliases for custom format strings that are defined by properties of the DateTimeFormatInfo object. 自訂格式字串也提供極大的彈性,來提供應用程式定義的數值或日期和時間值格式。Custom format strings also offer considerable flexibility in providing application-defined formatting for numeric values or date and time values. 您可以將多個自訂格式規範結合成單一自訂格式字串,以自訂您的數值及日期和時間值結果字串。You can define your own custom result strings for both numeric values and date and time values by combining multiple custom format specifiers into a single custom format string. 下列範例定義的自訂格式字串,會在月份名稱、日期和年後面顯示加上括號的星期。The following example defines a custom format string that displays the day of the week in parentheses after the month name, day, and year.

string customFormat = "MMMM dd, yyyy (dddd)";
DateTime date1 = new DateTime(2009, 8, 28);
Console.WriteLine(date1.ToString(customFormat));   
// The example displays the following output if run on a system
// whose language is English:
//       August 28, 2009 (Friday)      
Dim customFormat As String = "MMMM dd, yyyy (dddd)"
Dim date1 As Date = #8/28/2009#
Console.WriteLine(date1.ToString(customFormat))   
' The example displays the following output if run on a system
' whose language is English:
'       August 28, 2009 (Friday)      

下列範例會定義自訂格式字串,該字串會將 Int64 值顯示為標準的七位數美國電話號碼且包含其區碼。The following example defines a custom format string that displays an Int64 value as a standard, seven-digit U.S. telephone number along with its area code.

using System;

public class Example
{
   public static void Main()
   {
      long number = 8009999999;
      string fmt = "000-000-0000";
      Console.WriteLine(number.ToString(fmt));
   }
}
// The example displays the following output:
//        800-999-9999
Module Example
   Public Sub Main()
      Dim number As Long = 8009999999
      Dim fmt As String = "000-000-0000"
      Console.WriteLine(number.ToString(fmt))
   End Sub
End Module
' The example displays the following output:

' The example displays the following output:
'       800-999-9999

雖然標準格式字串通常能夠為應用程式定義的類型解決大部分的格式需求,但您也可以定義自訂格式規範來格式化您的類型。Although standard format strings can generally handle most of the formatting needs for your application-defined types, you may also define custom format specifiers to format your types.

格式字串和 .NET 類型Format Strings and .NET Types

所有數字類型 (也就是 ByteDecimalDoubleInt16Int32Int64SByteSingleUInt16UInt32UInt64BigInteger 類型),以及 DateTimeDateTimeOffsetTimeSpanGuid 和所有列舉類型,都支援以格式字串進行格式化。All numeric types (that is, the Byte, Decimal, Double, Int16, Int32, Int64, SByte, Single, UInt16, UInt32, UInt64, and BigInteger types), as well as the DateTime, DateTimeOffset, TimeSpan, Guid, and all enumeration types, support formatting with format strings. 如需每個類型所支援特定格式字串的資訊,請參閱下列主題:For information on the specific format strings supported by each type, see the following topics:

標題Title 定義Definition
Standard Numeric Format StringsStandard Numeric Format Strings 說明建立數值常用之字串表示的標準格式字串。Describes standard format strings that create commonly used string representations of numeric values.
Custom Numeric Format StringsCustom Numeric Format Strings 說明建立應用程式專屬數值格式的自訂格式字串。Describes custom format strings that create application-specific formats for numeric values.
標準日期和時間格式字串Standard Date and Time Format Strings 說明建立 DateTimeDateTimeOffset 值之常用字串表示的標準格式字串。Describes standard format strings that create commonly used string representations of DateTime and DateTimeOffset values.
自訂日期和時間格式字串Custom Date and Time Format Strings 說明建立應用程式專屬 DateTimeDateTimeOffset 值格式的自訂格式字串。Describes custom format strings that create application-specific formats for DateTime and DateTimeOffset values.
標準 TimeSpan 格式字串Standard TimeSpan Format Strings 說明建立時間間隔之常用字串表示的標準格式字串。Describes standard format strings that create commonly used string representations of time intervals.
自訂 TimeSpan 格式字串Custom TimeSpan Format Strings 說明建立應用程式專屬數值格式的自訂格式字串。Describes custom format strings that create application-specific formats for time intervals.
Enumeration Format StringsEnumeration Format Strings 說明用來建立列舉值之字串表示的標準格式字串。Describes standard format strings that are used to create string representations of enumeration values.
Guid.ToString(String) 描述 Guid 值的標準格式字串。Describes standard format strings for Guid values.

以格式提供者和 IFormatProvider 介面進行符合文化特性的格式化Culture-Sensitive Formatting with Format Providers and the IFormatProvider Interface

雖然格式規範可讓您自訂物件的格式,但如果要為物件產生有意義的字串表示,您通常還需要其他格式設定資訊。Although format specifiers let you customize the formatting of objects, producing a meaningful string representation of objects often requires additional formatting information. 例如,如果要使用 "C" 標準格式字串或自訂格式字串 (例如 "$ #,#.00") 將數字格式化為貨幣值,您至少還需要有正確的貨幣符號、群組分隔符號和小數分隔符號的相關資訊。For example, formatting a number as a currency value by using either the "C" standard format string or a custom format string such as "$ #,#.00" requires, at a minimum, information about the correct currency symbol, group separator, and decimal separator to be available to include in the formatted string. 在 .NET 中,這項額外的格式資訊是透過 IFormatProvider 介面取得,而這個介面會當做傳遞至數字類型以及日期和時間類型的 ToString 方法之一個或多個多載的參數來提供。In .NET, this additional formatting information is made available through the IFormatProvider interface, which is provided as a parameter to one or more overloads of the ToString method of numeric types and date and time types. IFormatProvider 實作會在 .NET 中用來支援文化特性特定的格式。IFormatProvider implementations are used in .NET to support culture-specific formatting. 下列範例將示範以代表不同文化特性的三個 IFormatProvider 物件進行格式化時,物件的字串表示會有什麼樣的變化。The following example illustrates how the string representation of an object changes when it is formatted with three IFormatProvider objects that represent different cultures.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      decimal value = 1603.42m;
      Console.WriteLine(value.ToString("C3", new CultureInfo("en-US")));
      Console.WriteLine(value.ToString("C3", new CultureInfo("fr-FR")));
      Console.WriteLine(value.ToString("C3", new CultureInfo("de-DE")));
   }
}
// The example displays the following output:
//       $1,603.420
//       1 603,420 €
//       1.603,420 €
Imports System.Globalization

Public Module Example
   Public Sub Main()
      Dim value As Decimal = 1603.42d
      Console.WriteLine(value.ToString("C3", New CultureInfo("en-US")))
      Console.WriteLine(value.ToString("C3", New CultureInfo("fr-FR")))
      Console.WriteLine(value.ToString("C3", New CultureInfo("de-DE")))
   End Sub
End Module
' The example displays the following output:
'       $1,603.420
'       1 603,420 €
'       1.603,420 €

IFormatProvider 介面包含一個 GetFormat(Type)方法,這個方法具有單一參數來指定可提供格式設定資訊之物件的類型。The IFormatProvider interface includes one method, GetFormat(Type), which has a single parameter that specifies the type of object that provides formatting information. 如果這個方法可以提供該類型的物件,則會傳回該物件。If the method can provide an object of that type, it returns it. 否則會傳回 null 參考 (在 Visual Basic 中為Nothing )。Otherwise, it returns a null reference (Nothing in Visual Basic).

IFormatProvider.GetFormat 是一種回呼方法。IFormatProvider.GetFormat is a callback method. 當您呼叫包含 ToString 參數的 IFormatProvider 方法多載時,這個多載會呼叫該 GetFormat 物件的 IFormatProvider 方法。When you call a ToString method overload that includes an IFormatProvider parameter, it calls the GetFormat method of that IFormatProvider object. GetFormat 方法負責將提供必要格式設定資訊的物件 (由其 formatType 參數指定),傳回給 ToString 方法。The GetFormat method is responsible for returning an object that provides the necessary formatting information, as specified by its formatType parameter, to the ToString method.

有幾個格式化或字串轉換方法都包含 IFormatProvider類型的參數,但通常呼叫方法時,會忽略這個參數的值。A number of formatting or string conversion methods include a parameter of type IFormatProvider, but in many cases the value of the parameter is ignored when the method is called. 下表列出一些使用這個參數的格式化方法,以及這些方法傳遞至 Type 方法的 IFormatProvider.GetFormat 物件的類型。The following table lists some of the formatting methods that use the parameter and the type of the Type object that they pass to the IFormatProvider.GetFormat method.

方法Method formatType 參數的類型Type of formatType parameter
數字類型的ToString 方法ToString method of numeric types System.Globalization.NumberFormatInfo
日期和時間類型的ToString 方法ToString method of date and time types System.Globalization.DateTimeFormatInfo
String.Format System.ICustomFormatter
StringBuilder.AppendFormat System.ICustomFormatter

注意

數字類型及日期和時間類型的 ToString 方法都含有多載,而其中只有某些多載會包含 IFormatProvider 參數。The ToString methods of the numeric types and date and time types are overloaded, and only some of the overloads include an IFormatProvider parameter. 如果方法沒有 IFormatProvider類型的參數,則會改以傳遞 CultureInfo.CurrentCulture 屬性所傳回的物件。If a method does not have a parameter of type IFormatProvider, the object that is returned by the CultureInfo.CurrentCulture property is passed instead. 例如,呼叫預設的 Int32.ToString() 方法最終會產生如下的方法呼叫: Int32.ToString("G", System.Globalization.CultureInfo.CurrentCulture)For example, a call to the default Int32.ToString() method ultimately results in a method call such as the following: Int32.ToString("G", System.Globalization.CultureInfo.CurrentCulture).

.NET 提供三個實作 IFormatProvider 的類別:.NET provides three classes that implement IFormatProvider:

您也可以實作自己的格式提供者來取代上述任何一個類別。You can also implement your own format provider to replace any one of these classes. 不過,您實作的 GetFormat 方法如果必須提供格式設定資訊給 ToString 方法,則必須傳回上表所列之類型的物件。However, your implementation’s GetFormat method must return an object of the type listed in the previous table if it has to provide formatting information to the ToString method.

符合文化特性的數值格式Culture-Sensitive Formatting of Numeric Values

根據預設,數值格式會區分文化特性。By default, the formatting of numeric values is culture-sensitive. 如果當您呼叫格式化方法時未指定文化特性,則會使用目前執行緒文化特性的格式設定慣例。If you do not specify a culture when you call a formatting method, the formatting conventions of the current thread culture are used. 下列範例將說明這種情形,其中目前執行緒文化特性會變更四次,然後呼叫 Decimal.ToString(String) 方法。This is illustrated in the following example, which changes the current thread culture four times and then calls the Decimal.ToString(String) method. 在各案例中,結果字串都會反映目前文化特性的格式設定慣例。In each case, the result string reflects the formatting conventions of the current culture. 這是因為 ToStringToString(String) 方法會包裝對每個數值類型之 ToString(String, IFormatProvider) 方法的呼叫。This is because the ToString and ToString(String) methods wrap calls to each numeric type's ToString(String, IFormatProvider) method.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      string[] cultureNames = { "en-US", "fr-FR", "es-MX", "de-DE" };
      Decimal value = 1043.17m;
      
      foreach (var cultureName in cultureNames) {
         // Change the current thread culture.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName);
         Console.WriteLine("The current culture is {0}", 
                           Thread.CurrentThread.CurrentCulture.Name);
         Console.WriteLine(value.ToString("C2"));
         Console.WriteLine();
      }   
   }
}
// The example displays the following output:
//       The current culture is en-US
//       $1,043.17
//       
//       The current culture is fr-FR
//       1 043,17 €
//       
//       The current culture is es-MX
//       $1,043.17
//       
//       The current culture is de-DE
//       1.043,17 €
Imports System.Globalization
Imports System.Threading 

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "fr-FR", "es-MX", "de-DE" }
      Dim value As Decimal = 1043.17d 
      
      For Each cultureName In cultureNames
         ' Change the current thread culture.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName)
         Console.WriteLine("The current culture is {0}", 
                           Thread.CurrentThread.CurrentCulture.Name)
         Console.WriteLine(value.ToString("C2"))
         Console.WriteLine()
      Next                  
   End Sub
End Module
' The example displays the following output:
'       The current culture is en-US
'       $1,043.17
'       
'       The current culture is fr-FR
'       1 043,17 €
'       
'       The current culture is es-MX
'       $1,043.17
'       
'       The current culture is de-DE
'       1.043,17 €

您也可以呼叫具有 ToString 參數的 provider 多載並且將下列任一項傳遞給它,藉此格式化特定文化特性的數值:You can also format a numeric value for a specific culture by calling a ToString overload that has a provider parameter and passing it either of the following:

下列範例將使用 NumberFormatInfo 物件,該物件表示用於格式化浮點數的英文 (美國) 和英文 (英國) 文化特性,以及法文和俄文中性文化特性。The following example uses NumberFormatInfo objects that represent the English (United States) and English (Great Britain) cultures and the French and Russian neutral cultures to format a floating-point number.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {                                                                                                    
      Double value = 1043.62957;
      string[] cultureNames = { "en-US", "en-GB", "ru", "fr" };
      
      foreach (var name in cultureNames) {
         NumberFormatInfo nfi = CultureInfo.CreateSpecificCulture(name).NumberFormat;
         Console.WriteLine("{0,-6} {1}", name + ":", value.ToString("N3", nfi));
      }   
   }
}
// The example displays the following output:
//       en-US: 1,043.630
//       en-GB: 1,043.630
//       ru:    1 043,630
//       fr:    1 043,630
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim value As Double = 1043.62957
      Dim cultureNames() As String = { "en-US", "en-GB", "ru", "fr" }
      
      For Each name In cultureNames
         Dim nfi As NumberFormatInfo = CultureInfo.CreateSpecificCulture(name).NumberFormat
         Console.WriteLine("{0,-6} {1}", name + ":", value.ToString("N3", nfi))
      Next   
   End Sub
End Module
' The example displays the following output:
'       en-US: 1,043.630
'       en-GB: 1,043.630
'       ru:    1 043,630
'       fr:    1 043,630

符合文化特性的日期和時間值格式Culture-Sensitive Formatting of Date and Time Values

根據預設,日期和時間值的格式區分文化特性。By default, the formatting of date and time values is culture-sensitive. 如果當您呼叫格式化方法時未指定文化特性,則會使用目前執行緒文化特性的格式設定慣例。If you do not specify a culture when you call a formatting method, the formatting conventions of the current thread culture are used. 下列範例將說明這種情形,其中目前執行緒文化特性會變更四次,然後呼叫 DateTime.ToString(String) 方法。This is illustrated in the following example, which changes the current thread culture four times and then calls the DateTime.ToString(String) method. 在各案例中,結果字串都會反映目前文化特性的格式設定慣例。In each case, the result string reflects the formatting conventions of the current culture. 這是因為 DateTime.ToString()DateTime.ToString(String)DateTimeOffset.ToString()DateTimeOffset.ToString(String) 方法會包裝 DateTime.ToString(String, IFormatProvider)DateTimeOffset.ToString(String, IFormatProvider) 方法的呼叫。This is because the DateTime.ToString(), DateTime.ToString(String), DateTimeOffset.ToString(), and DateTimeOffset.ToString(String) methods wrap calls to the DateTime.ToString(String, IFormatProvider) and DateTimeOffset.ToString(String, IFormatProvider) methods.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      string[] cultureNames = { "en-US", "fr-FR", "es-MX", "de-DE" };
      DateTime dateToFormat = new DateTime(2012, 5, 28, 11, 30, 0);
      
      foreach (var cultureName in cultureNames) {
         // Change the current thread culture.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName);
         Console.WriteLine("The current culture is {0}", 
                           Thread.CurrentThread.CurrentCulture.Name);
         Console.WriteLine(dateToFormat.ToString("F"));
         Console.WriteLine();
      }   
   }
}
// The example displays the following output:
//       The current culture is en-US
//       Monday, May 28, 2012 11:30:00 AM
//       
//       The current culture is fr-FR
//       lundi 28 mai 2012 11:30:00
//       
//       The current culture is es-MX
//       lunes, 28 de mayo de 2012 11:30:00 a.m.
//       
//       The current culture is de-DE
//       Montag, 28. Mai 2012 11:30:00
Imports System.Globalization
Imports System.Threading 

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "fr-FR", "es-MX", "de-DE" }
      Dim dateToFormat As Date = #5/28/2012 11:30AM#
      
      For Each cultureName In cultureNames
         ' Change the current thread culture.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName)
         Console.WriteLine("The current culture is {0}", 
                           Thread.CurrentThread.CurrentCulture.Name)
         Console.WriteLine(dateToFormat.ToString("F"))
         Console.WriteLine()
      Next                  
   End Sub
End Module
' The example displays the following output:
'       The current culture is en-US
'       Monday, May 28, 2012 11:30:00 AM
'       
'       The current culture is fr-FR
'       lundi 28 mai 2012 11:30:00
'       
'       The current culture is es-MX
'       lunes, 28 de mayo de 2012 11:30:00 a.m.
'       
'       The current culture is de-DE
'       Montag, 28. Mai 2012 11:30:00 

您也可以呼叫具有 DateTime.ToString 參數的 DateTimeOffset.ToStringprovider 多載並且將下列任一項傳遞給它,藉此格式化特定文化特性的日期和時間值:You can also format a date and time value for a specific culture by calling a DateTime.ToString or DateTimeOffset.ToString overload that has a provider parameter and passing it either of the following:

下列範例將使用 DateTimeFormatInfo 物件,該物件表示用於格式化日期的英文 (美國) 和英文 (英國) 文化特性,以及法文和俄文中性文化特性。The following example uses DateTimeFormatInfo objects that represent the English (United States) and English (Great Britain) cultures and the French and Russian neutral cultures to format a date.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {                                                                                                    
      DateTime dat1 = new DateTime(2012, 5, 28, 11, 30, 0);
      string[] cultureNames = { "en-US", "en-GB", "ru", "fr" };
      
      foreach (var name in cultureNames) {
         DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture(name).DateTimeFormat;
         Console.WriteLine("{0}: {1}", name, dat1.ToString(dtfi));
      }   
   }
}
// The example displays the following output:
//       en-US: 5/28/2012 11:30:00 AM
//       en-GB: 28/05/2012 11:30:00
//       ru: 28.05.2012 11:30:00
//       fr: 28/05/2012 11:30:00
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dat1 As Date = #5/28/2012 11:30AM#
      Dim cultureNames() As String = { "en-US", "en-GB", "ru", "fr" }
      
      For Each name In cultureNames
         Dim dtfi As DateTimeFormatInfo = CultureInfo.CreateSpecificCulture(name).DateTimeFormat
         Console.WriteLine("{0}: {1}", name, dat1.ToString(dtfi))
      Next   
   End Sub
End Module
' The example displays the following output:
'       en-US: 5/28/2012 11:30:00 AM
'       en-GB: 28/05/2012 11:30:00
'       ru: 28.05.2012 11:30:00
'       fr: 28/05/2012 11:30:00

IFormattable 介面The IFormattable Interface

以格式字串和 ToString 參數來多載 IFormatProvider 方法的類型,通常也會實作 IFormattable 介面。Typically, types that overload the ToString method with a format string and an IFormatProvider parameter also implement the IFormattable interface. 這個介面具有單一成員 IFormattable.ToString(String, IFormatProvider),這個成員同時包含格式字串和格式提供者做為參數。This interface has a single member, IFormattable.ToString(String, IFormatProvider), that includes both a format string and a format provider as parameters.

針對您的應用程式定義的類別來實作 IFormattable 介面有兩項好處:Implementing the IFormattable interface for your application-defined class offers two advantages:

下列範例定義一個實作 Temperature 介面的 IFormattable 類別。The following example defines a Temperature class that implements the IFormattable interface. 這個類別支援 "C" 或 "G" 格式規範來顯示攝氏溫度、支援 "F" 格式規範來顯示華氏溫度,也支援 "K" 格式規範來顯示絕對溫度。It supports the "C" or "G" format specifiers to display the temperature in Celsius, the "F" format specifier to display the temperature in Fahrenheit, and the "K" format specifier to display the temperature in Kelvin.

using System;
using System.Globalization;

public class Temperature : IFormattable
{
   private decimal m_Temp;

   public Temperature(decimal temperature)
   {
      this.m_Temp = temperature;
   }
   
   public decimal Celsius
   {
      get { return this.m_Temp; }
   }
   
   public decimal Kelvin
   {
      get { return this.m_Temp + 273.15m; }   
   }
   
   public decimal Fahrenheit
   {
      get { return Math.Round((decimal) this.m_Temp * 9 / 5 + 32, 2); }
   }

   public override string ToString()
   {
      return this.ToString("G", null);
   }
   
   public string ToString(string format)
   {
      return this.ToString(format, null);
   }
   
   public string ToString(string format, IFormatProvider provider)  
   {
      // Handle null or empty arguments.
      if (String.IsNullOrEmpty(format))
         format = "G";
      // Remove any white space and covert to uppercase.
      format = format.Trim().ToUpperInvariant();

      if (provider == null)
         provider = NumberFormatInfo.CurrentInfo;
            
      switch (format)
      {
         // Convert temperature to Fahrenheit and return string.
         case "F":
            return this.Fahrenheit.ToString("N2", provider) + "°F";
         // Convert temperature to Kelvin and return string.
         case "K":
            return this.Kelvin.ToString("N2", provider) + "K";
         // Return temperature in Celsius.
         case "C":
         case "G":
            return this.Celsius.ToString("N2", provider) + "°C";
         default:
            throw new FormatException(String.Format("The '{0}' format string is not supported.", format));
      }      
   }
}
Imports System.Globalization

Public Class Temperature : Implements IFormattable
   Private m_Temp As Decimal

   Public Sub New(temperature As Decimal)
      Me.m_Temp = temperature
   End Sub
   
   Public ReadOnly Property Celsius() As Decimal
      Get
         Return Me.m_Temp
      End Get   
   End Property
   
   Public ReadOnly Property Kelvin() As Decimal
      Get
         Return Me.m_Temp + 273.15d   
      End Get
   End Property
   
   Public ReadOnly Property Fahrenheit() As Decimal
      Get
         Return Math.Round(CDec(Me.m_Temp * 9 / 5 + 32), 2)
      End Get      
   End Property

   Public Overrides Function ToString() As String
      Return Me.ToString("G", Nothing)
   End Function
   
   Public Overloads Function ToString(format As String) As String
      Return Me.ToString(format, Nothing)
   End Function
   
   Public Overloads Function ToString(format As String, provider As IFormatProvider) As String _  
      Implements IFormattable.ToString

      ' Handle null or empty arguments.
      If String.IsNullOrEmpty(format) Then format = "G"
      ' Remove any white space and convert to uppercase.
      format = format.Trim().ToUpperInvariant()

      If provider Is Nothing Then provider = NumberFormatInfo.CurrentInfo
            
      Select Case format
         ' Convert temperature to Fahrenheit and return string.
         Case "F"
            Return Me.Fahrenheit.ToString("N2", provider) & "°F"
         ' Convert temperature to Kelvin and return string.
         Case "K"
            Return Me.Kelvin.ToString("N2", provider) & "K"
         ' Return temperature in Celsius.
         Case "C", "G"
            Return Me.Celsius.ToString("N2", provider) & "°C"
         Case Else
            Throw New FormatException(String.Format("The '{0}' format string is not supported.", format))
      End Select      
   End Function
End Class

下列範例會執行個體化 Temperature 物件。The following example instantiates a Temperature object. 然後呼叫 ToString 方法,並使用數個複合格式字串來取得 Temperature 物件的不同字串表示。It then calls the ToString method and uses several composite format strings to obtain different string representations of a Temperature object. 其中每個方法又呼叫 IFormattable 類別的 Temperature 實作。Each of these method calls, in turn, calls the IFormattable implementation of the Temperature class.

public class Example
{
   public static void Main()
   {
      CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
      Temperature temp = new Temperature(22m);
      Console.WriteLine(Convert.ToString(temp, new CultureInfo("ja-JP")));
      Console.WriteLine("Temperature: {0:K}", temp);
      Console.WriteLine("Temperature: {0:F}", temp);
      Console.WriteLine(String.Format(new CultureInfo("fr-FR"), "Temperature: {0:F}", temp));
   }
}
// The example displays the following output:
//       22.00°C
//       Temperature: 295.15K
//       Temperature: 71.60°F
//       Temperature: 71,60°F
Public Module Example
   Public Sub Main()
      Dim temp As New Temperature(22d)
      CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US")
      Console.WriteLine(Convert.ToString(temp1, New CultureInfo("ja-JP")))
      Console.WriteLine("Temperature: {0:K}", temp)
      Console.WriteLine("Temperature: {0:F}", temp)
      Console.WriteLine(String.Format(New CultureInfo("fr-FR"), "Temperature: {0:F}", temp)) 
   End Sub
End Module
' The example displays the following output:
'       22.00°C
'       Temperature: 295.15K
'       Temperature: 71.60°F
'       Temperature: 71,60°F

複合格式Composite Formatting

某些方法 (例如 String.FormatStringBuilder.AppendFormat) 支援複合格式。Some methods, such as String.Format and StringBuilder.AppendFormat, support composite formatting. 複合格式字串是一種範本,可傳回由零個、一個或更多物件的字串表示所組成的單一字串。A composite format string is a kind of template that returns a single string that incorporates the string representation of zero, one, or more objects. 複合格式字串中的每個物件都以有索引的格式項目來表示。Each object is represented in the composite format string by an indexed format item. 格式項目的索引對應至其所表示的物件在方法的參數清單中的位置。The index of the format item corresponds to the position of the object that it represents in the method's parameter list. 索引以零為起始。Indexes are zero-based. 例如,在下列對 String.Format 方法的呼叫中,第一個格式項目 {0:D}thatDate 的字串表示所取代、第二個格式項目 {1}item1 的字串表示所取代,而第三個格式項目 {2:C2}item1.Value 的字串表示所取代。For example, in the following call to the String.Format method, the first format item, {0:D}, is replaced by the string representation of thatDate; the second format item, {1}, is replaced by the string representation of item1; and the third format item, {2:C2}, is replaced by the string representation of item1.Value.

result = String.Format("On {0:d}, the inventory of {1} was worth {2:C2}.", 
                       thatDate, item1, item1.Value);
Console.WriteLine(result);                            
// The example displays output like the following if run on a system
// whose current culture is en-US:
//       On 5/1/2009, the inventory of WidgetA was worth $107.44.
result = String.Format("On {0:d}, the inventory of {1} was worth {2:C2}.", _
                       thatDate, item1, item1.Value)
Console.WriteLine(result)                            
' The example displays output like the following if run on a system
' whose current culture is en-US:
'       On 5/1/2009, the inventory of WidgetA was worth $107.44.

除了取代具有對應物件字串表示格式的項目,格式項目也可讓您控制下列幾項:In addition to replacing a format item with the string representation of its corresponding object, format items also let you control the following:

  • 當物件實作 IFormattable 介面,並支援格式字串時,物件表示為字串的特定方式。The specific way in which an object is represented as a string, if the object implements the IFormattable interface and supports format strings. 您可將格式項目索引後面接上 : (冒號) ,後面再接有效的格式字串,以執行此作業。You do this by following the format item's index with a : (colon) followed by a valid format string. 前一個範例採用的方法是用 "d" (簡短日期模式) 格式字串來格式化日期值 (例如 {0:d}) 以及用 "C2" 格式字串 (例如 {2:C2} ) 來格式化數值,以表示具有兩個小數位數的十進位數字之貨幣值。The previous example did this by formatting a date value with the "d" (short date pattern) format string (e.g., {0:d}) and by formatting a numeric value with the "C2" format string (e.g., {2:C2} to represent the number as a currency value with two fractional decimal digits.

  • 包含物件字串表示法及在該欄位中對齊方式的字串表示法之欄位寬度。The width of the field that contains the object's string representation, and the alignment of the string representation in that field. 您可將格式項目索引後面接上 , (逗號) ,後面再接欄位寬度,以執行此作業。You do this by following the format item's index with a , (comma) followed the field width. 如果欄位寬度是正值,則此欄位中的字串為靠右對齊;如果欄位寬度是負值,則為靠左對齊。The string is right-aligned in the field if the field width is a positive value, and it is left-aligned if the field width is a negative value. 下列範例在長 20 個字元的欄位中將日期值靠左對齊,並在長 11 個字元的欄位中將具有一位小數位數的十進位值靠右對齊。The following example left-aligns date values in a 20-character field, and it right-aligns decimal values with one fractional digit in an 11-character field.

    DateTime startDate = new DateTime(2015, 8, 28, 6, 0, 0);
    decimal[] temps = { 73.452m, 68.98m, 72.6m, 69.24563m,
                       74.1m, 72.156m, 72.228m };
    Console.WriteLine("{0,-20} {1,11}\n", "Date", "Temperature");
    for (int ctr = 0; ctr < temps.Length; ctr++)
       Console.WriteLine("{0,-20:g} {1,11:N1}", startDate.AddDays(ctr), temps[ctr]);
    
    // The example displays the following output:
    //       Date                 Temperature
    //
    //       8/28/2015 6:00 AM           73.5
    //       8/29/2015 6:00 AM           69.0
    //       8/30/2015 6:00 AM           72.6
    //       8/31/2015 6:00 AM           69.2
    //       9/1/2015 6:00 AM            74.1
    //       9/2/2015 6:00 AM            72.2
    //       9/3/2015 6:00 AM            72.2
    
    Dim startDate As New Date(2015, 8, 28, 6, 0, 0)
    Dim temps() As Decimal = { 73.452, 68.98, 72.6, 69.24563,
                               74.1, 72.156, 72.228 }
    Console.WriteLine("{0,-20} {1,11}", "Date", "Temperature")
    Console.WriteLine()
    For ctr As Integer = 0 To temps.Length - 1
       Console.WriteLine("{0,-20:g} {1,11:N1}", startDate.AddDays(ctr), temps(ctr))
    Next
    ' The example displays the following output:
    '       Date                 Temperature
    '
    '       8/28/2015 6:00 AM           73.5
    '       8/29/2015 6:00 AM           69.0
    '       8/30/2015 6:00 AM           72.6
    '       8/31/2015 6:00 AM           69.2
    '       9/1/2015 6:00 AM            74.1
    '       9/2/2015 6:00 AM            72.2
    '       9/3/2015 6:00 AM            72.2
    

    請注意如果對齊字串元件和格式字串元件都存在,則前者優先於後者 (例如, {0,-20:g})。Note that, if both the alignment string component and the format string component are present, the former precedes the latter (for example, {0,-20:g}.

如需複合格式的詳細資訊,請參閱 Composite FormattingFor more information about composite formatting, see Composite Formatting.

使用 ICustomFormatter 的自訂格式Custom Formatting with ICustomFormatter

String.Format(IFormatProvider, String, Object[])StringBuilder.AppendFormat(IFormatProvider, String, Object[])這兩個複合格式方法包含支援自訂格式的格式提供者參數。Two composite formatting methods, String.Format(IFormatProvider, String, Object[]) and StringBuilder.AppendFormat(IFormatProvider, String, Object[]), include a format provider parameter that supports custom formatting. 呼叫這兩種格式化方法的任一種時,會將表示 Type 介面的 ICustomFormatter 物件傳遞至格式提供者的 GetFormat 方法。When either of these formatting methods is called, it passes a Type object that represents an ICustomFormatter interface to the format provider’s GetFormat method. 然後, GetFormat 方法負責傳回 ICustomFormatter 實作,這個實作提供自訂格式。The GetFormat method is then responsible for returning the ICustomFormatter implementation that provides custom formatting.

ICustomFormatter 介面具有單一方法 Format(String, Object, IFormatProvider),複合格式化方法會自動針對複合格式字串中的每個格式項目,各呼叫一次這個方法。The ICustomFormatter interface has a single method, Format(String, Object, IFormatProvider), that is called automatically by a composite formatting method, once for each format item in a composite format string. Format(String, Object, IFormatProvider) 方法具有三個參數:格式字串 (表示格式項目中的 formatString 引數)、要格式化的物件,以及提供格式化服務的 IFormatProvider 物件。The Format(String, Object, IFormatProvider) method has three parameters: a format string, which represents the formatString argument in a format item, an object to format, and an IFormatProvider object that provides formatting services. 實作 ICustomFormatter 的物件通常也會實作 IFormatProvider,所以這最後一個參數是對自訂格式化類別的參考。Typically, the class that implements ICustomFormatter also implements IFormatProvider, so this last parameter is a reference to the custom formatting class itself. 方法會傳回要格式化之物件的自訂格式化字串表示。The method returns a custom formatted string representation of the object to be formatted. 如果方法無法格式化物件,則應該傳回 null 參考 (在 Visual Basic 中為Nothing )。If the method cannot format the object, it should return a null reference (Nothing in Visual Basic).

下列範例提供一個名為 ICustomFormatterByteByByteFormatter 實作,這個實作會將整數值顯示為一連串由兩位數十六進位值再加上一個空格所組成的數列。The following example provides an ICustomFormatter implementation named ByteByByteFormatter that displays integer values as a sequence of two-digit hexadecimal values followed by a space.

public class ByteByByteFormatter : 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 (! formatProvider.Equals(this)) return null;
      
      // Handle only hexadecimal format string.
      if (! format.StartsWith("X")) return null;
      
      byte[] bytes;
      string output = null;
      
      // Handle only integral types.
      if (arg is Byte) 
         bytes = BitConverter.GetBytes((Byte) arg);
      else if (arg is Int16)
         bytes = BitConverter.GetBytes((Int16) arg);
      else if (arg is Int32)
         bytes = BitConverter.GetBytes((Int32) arg);
      else if (arg is Int64)   
         bytes = BitConverter.GetBytes((Int64) arg);
      else if (arg is SByte)
         bytes = BitConverter.GetBytes((SByte) arg);
      else if (arg is UInt16)
         bytes = BitConverter.GetBytes((UInt16) arg);
      else if (arg is UInt32)
         bytes = BitConverter.GetBytes((UInt32) arg);
      else if (arg is UInt64)
         bytes = BitConverter.GetBytes((UInt64) arg);
      else
         return null;

      for (int ctr = bytes.Length - 1; ctr >= 0; ctr--)
         output += String.Format("{0:X2} ", bytes[ctr]);   
      
      return output.Trim();
   }
}
Public Class ByteByByteFormatter : 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, arg As Object, 
                          formatProvider As IFormatProvider) As String _
                          Implements ICustomFormatter.Format

      If Not formatProvider.Equals(Me) Then Return Nothing

      ' Handle only hexadecimal format string.
      If Not fmt.StartsWith("X") Then 
            Return Nothing
      End If

      ' Handle only integral types.
      If Not typeof arg Is Byte AndAlso
         Not typeof arg Is Int16 AndAlso
         Not typeof arg Is Int32 AndAlso
         Not typeof arg Is Int64 AndAlso
         Not typeof arg Is SByte AndAlso
         Not typeof arg Is UInt16 AndAlso
         Not typeof arg Is UInt32 AndAlso
         Not typeof arg Is UInt64 Then _
            Return Nothing

      Dim bytes() As Byte = BitConverter.GetBytes(arg)
      Dim output As String = Nothing
         
      For ctr As Integer = bytes.Length - 1 To 0 Step -1
         output += String.Format("{0:X2} ", bytes(ctr))   
      Next
      
      Return output.Trim()
   End Function
End Class

下列範例會使用 ByteByByteFormatter 類別來格式化整數值。The following example uses the ByteByByteFormatter class to format integer values. 請注意,在範例中不會明確呼叫 ICustomFormatter.Format 方法在第二個 String.Format(IFormatProvider, String, Object[]) 方法呼叫中被呼叫不只一次,且第三個方法呼叫中使用預設 NumberFormatInfo 提供者,因為ByteByByteFormatter.FormatNote that the ICustomFormatter.Format method is called more than once in the second String.Format(IFormatProvider, String, Object[]) method call, and that the default NumberFormatInfo provider is used in the third method call because the .ByteByByteFormatter.Format 方法無法辨認 "N0" 格式字串而傳回 null 參考 (在 Visual Basic 中為Nothing ) 的格式規範。method does not recognize the "N0" format string and returns a null reference (Nothing in Visual Basic).

public class Example
{
   public static void Main()
   {
      long value = 3210662321; 
      byte value1 = 214;
      byte value2 = 19;
      
      Console.WriteLine(String.Format(new ByteByByteFormatter(), "{0:X}", value));
      Console.WriteLine(String.Format(new ByteByByteFormatter(), "{0:X} And {1:X} = {2:X} ({2:000})", 
                                      value1, value2, value1 & value2));                                
      Console.WriteLine(String.Format(new ByteByByteFormatter(), "{0,10:N0}", value));
   }
}
// The example displays the following output:
//       00 00 00 00 BF 5E D1 B1
//       00 D6 And 00 13 = 00 12 (018)
//       3,210,662,321
Public Module Example
   Public Sub Main()
      Dim value As Long = 3210662321 
      Dim value1 As Byte = 214
      Dim value2 As Byte = 19
      
      Console.WriteLine((String.Format(New ByteByByteFormatter(), "{0:X}", value)))
      Console.WriteLine((String.Format(New ByteByByteFormatter(), "{0:X} And {1:X} = {2:X} ({2:000})", 
                                      value1, value2, value1 And value2)))                                
      Console.WriteLine(String.Format(New ByteByByteFormatter(), "{0,10:N0}", value))
   End Sub
End Module
' The example displays the following output:
'       00 00 00 00 BF 5E D1 B1
'       00 D6 And 00 13 = 00 12 (018)
'       3,210,662,321

標題Title 定義Definition
Standard Numeric Format StringsStandard Numeric Format Strings 說明建立數值常用之字串表示的標準格式字串。Describes standard format strings that create commonly used string representations of numeric values.
Custom Numeric Format StringsCustom Numeric Format Strings 說明建立應用程式專屬數值格式的自訂格式字串。Describes custom format strings that create application-specific formats for numeric values.
標準日期和時間格式字串Standard Date and Time Format Strings 說明建立 DateTime 值之常用字串表示的標準格式字串。Describes standard format strings that create commonly used string representations of DateTime values.
自訂日期和時間格式字串Custom Date and Time Format Strings 說明建立應用程式專屬 DateTime 值格式的自訂格式字串。Describes custom format strings that create application-specific formats for DateTime values.
標準 TimeSpan 格式字串Standard TimeSpan Format Strings 說明建立時間間隔之常用字串表示的標準格式字串。Describes standard format strings that create commonly used string representations of time intervals.
自訂 TimeSpan 格式字串Custom TimeSpan Format Strings 說明建立應用程式專屬數值格式的自訂格式字串。Describes custom format strings that create application-specific formats for time intervals.
Enumeration Format StringsEnumeration Format Strings 說明用來建立列舉值之字串表示的標準格式字串。Describes standard format strings that are used to create string representations of enumeration values.
複合格式Composite Formatting 描述如何將一個或更多的格式化值嵌入字串。Describes how to embed one or more formatted values in a string. 字串可以隨後顯示在主控台 (Console) 或寫入資料流。The string can subsequently be displayed on the console or written to a stream.
執行格式化作業Performing Formatting Operations 列出各主題,提供執行特定格式設定作業的逐步指示。Lists topics that provide step-by-step instructions for performing specific formatting operations.
Parsing StringsParsing Strings 說明如何將物件初始化為這些物件的字串表示所描述的值。Describes how to initialize objects to the values described by string representations of those objects. 剖析是格式化的反向作業。Parsing is the inverse operation of formatting.

參考資料Reference