共用方式為


概述:如何在 .NET 中設置數位、日期、枚舉和其他類型的格式

格式設置是將類或結構的實例或枚舉值轉換為字串表示形式的過程。 目的是向使用者顯示結果字串,或稍後對其進行反序列化以恢復原始數據類型。 本文介紹了 .NET 提供的格式設置機制。

備註

解析是格式設置的反面。 解析作從其字串表示形式創建數據類型的實例。 有關更多資訊,請參閱 解析字串。 有關序列化和反序列化的資訊,請參閱 .NET 中的序列化

格式設置的基本機制是該方法的預設 Object.ToString 實現,本主題後面的 “使用ToString 方法進行預設格式設置 ” 一節中對此進行了討論。 但是,.NET 提供了多種方法來修改和擴展其預設格式支援。 這些包括下列各項:

  • 重寫 Object.ToString 該方法以定義物件值的自定義字串表示形式。 有關詳細資訊,請參閱本主題後面的 覆蓋ToString方法 部分。

  • 定義格式說明符,使物件值的字串表示形式能夠採用多種形式。 例如,以下語句中的 「X」 格式說明符將整數轉換為十六進位值的字串表示形式。

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

    有關格式說明符的更多資訊,請參見 ToString 方法和格式字串 部分。

  • 使用格式提供程式實現特定區域性的格式約定。 例如,以下語句使用 en-US 區域性的格式約定顯示貨幣值。

    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
    

    有關使用格式提供程式進行格式設置的更多資訊,請參閱 格式提供程式 部分。

  • 實現 IFormattable 介面以支援使用 Convert class 和 composite 格式的字串轉換。 有關更多資訊,請參閱 IFormattable 介面 部分。

  • 使用複合格式將值的字串表示形式嵌入到較大的字串中。 有關更多資訊,請參閱 複合格式 部分。

  • 使用字串插值,這是一種可讀性更強的語法,可將值的字串表示形式嵌入到更大的字串中。 有關更多資訊,請參閱 字串插值

  • 實現 ICustomFormatterIFormatProvider 提供完整的自定義格式解決方案。 有關詳細資訊,請參閱 使用 ICustomFormatter 進行自定義格式 設置部分。

以下各節介紹將物件轉換為其字串表示形式的這些方法。

使用 ToString 方法的預設格式

派生自 System.Object 的每個類型都會自動繼承一個無 ToString 參數方法,預設情況下,該方法返回該類型的名稱。 以下示例說明了預設 ToString 方法。 它定義了一個沒有實現的類 name Automobile 。 當實例化類並調用其 ToString 方法時,它會顯示其類型名稱。 請注意, ToString 該方法在示例中未顯式調用。 該方法 Console.WriteLine(Object) 隱式調用 ToString 作為參數傳遞給它的物件的 method。

using System;

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

public class Example9
{
   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 Example9
    Public Sub Main9()
        Dim firstAuto As New Automobile()
        Console.WriteLine(firstAuto)
    End Sub
End Module
' The example displays the following output:
'       Automobile

警告

從 Windows 8.1 開始,Windows 運行時包括一個 IStringable 介面,該介面具有單個方法 IStringable.ToString,該方法提供預設格式設置支援。 但是,我們建議託管類型不要實現該 IStringable 介面。 有關詳細資訊,請參閱 Windows 運行時和 IStringable 介面

由於除介面以外的所有類型都是從 派生的 Object,因此此功能會自動提供給您的自定義類或結構。 但是,預設 ToString 方法提供的功能是有限的:儘管它標識了類型,但它無法提供有關該類型實例的任何資訊。 若要提供提供有關該物件的信息的物件的字串表示形式,必須重寫 ToString 該方法。

備註

結構繼承自 ValueType,而 又從 派生自 Object。 儘管 ValueType overrides Object.ToString,但其實現是相同的。

重寫 ToString 方法

顯示類型的名稱通常用途有限,並且不允許類型的消費者將一個實例與另一個實例區分開來。 但是,您可以覆蓋該方法 ToString 以提供更有用的物件值的表示形式。 下面的示例定義一個 Temperature 物件並覆蓋其 ToString 方法以攝氏度顯示溫度。

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 Example12
{
    public static void Main()
    {
        Temperature currentTemperature = new Temperature(23.6m);
        Console.WriteLine($"The current temperature is {currentTemperature}");
    }
}
// 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 Example13
    Public Sub Main13()
        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 每個基元值類型的方法都已被重寫,以顯示物件的值而不是其名稱。 下表顯示了每種基元類型的覆蓋。 請注意,大多數重寫的方法調用該方法的另一個 ToString 重載,並向其傳遞“G”格式說明符(定義其類型的常規格式)和 IFormatProvider 表示當前區域性的物件。

類型 ToString 覆蓋
Boolean 傳回 Boolean.TrueStringBoolean.FalseString
Byte 用於設置當前區域性值格式Byte的調用Byte.ToString("G", NumberFormatInfo.CurrentInfo)
Char 以字串形式返回字元。
DateTime 用於設置當前區域性的日期和時間值格式的調用 DateTime.ToString("G", DatetimeFormatInfo.CurrentInfo)
Decimal 用於設置當前區域性值格式Decimal的調用Decimal.ToString("G", NumberFormatInfo.CurrentInfo)
Double 用於設置當前區域性值格式Double的調用Double.ToString("G", NumberFormatInfo.CurrentInfo)
Int16 用於設置當前區域性值格式Int16的調用Int16.ToString("G", NumberFormatInfo.CurrentInfo)
Int32 用於設置當前區域性值格式Int32的調用Int32.ToString("G", NumberFormatInfo.CurrentInfo)
Int64 用於設置當前區域性值格式Int64的調用Int64.ToString("G", NumberFormatInfo.CurrentInfo)
SByte 用於設置當前區域性值格式SByte的調用SByte.ToString("G", NumberFormatInfo.CurrentInfo)
Single 用於設置當前區域性值格式Single的調用Single.ToString("G", NumberFormatInfo.CurrentInfo)
UInt16 用於設置當前區域性值格式UInt16的調用UInt16.ToString("G", NumberFormatInfo.CurrentInfo)
UInt32 用於設置當前區域性值格式UInt32的調用UInt32.ToString("G", NumberFormatInfo.CurrentInfo)
UInt64 用於設置當前區域性值格式UInt64的調用UInt64.ToString("G", NumberFormatInfo.CurrentInfo)

ToString 方法和格式字串

當物件具有單個字串表示形式時,依賴 default ToString 方法或覆蓋 ToString 是合適的。 但是,物件的值通常具有多種表示形式。 例如,溫度可以用華氏度、攝氏度或開爾文來表示。 同樣,整數值 10 可以用多種方式表示,包括 10、10.0、1.0e01 或 10.00 美元。

為了使單個值具有多個字串表示形式,.NET 使用格式字串。 格式字串是包含一個或多個預定義格式說明符的字串,這些說明符是定義方法應如何 ToString 設置其輸出格式的單個字元或字元組。 然後,格式字串將作為參數傳遞給物件 ToString 的方法,並確定該物件值的字串表示形式應如何顯示。

.NET 中的所有數值類型、日期和時間類型以及枚舉類型都支援一組預定義的格式說明符。 您還可以使用格式字串來定義應用程式定義的數據類型的多個字串表示形式。

標準格式字串

標準格式字串包含一個格式說明符,該格式說明符是一個字母字元,用於定義其所應用到的物件的字串表示形式,以及一個可選的精度說明符,該說明符會影響結果字元串中顯示的位數。 如果省略或不支援精度說明符,則標準格式說明符等效於標準格式字串。

.NET 為所有數字類型、所有日期和時間類型以及所有枚舉類型定義了一組標準格式說明符。 例如,這些類別中的每一個都支援“G”標準格式說明符,該說明符定義該類型值的常規字串表示形式。

枚舉類型的標準格式字串直接控制值的字串表示形式。 傳遞給枚舉值 ToString 方法的格式字串確定是使用其字串名稱(“G”和“F”格式說明符)、其基礎整數值(“D”格式說明符)還是其十六進位值(“X”格式說明符)來顯示該值。 下面的示例說明瞭如何使用標準格式字串來格式化 DayOfWeek 枚舉值。

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

有關枚舉格式字串的資訊,請參閱 枚舉格式字串

數值類型的標準格式字串通常定義一個結果字串,其精確外觀由一個或多個屬性值控制。 例如,“C” 格式說明符將數位格式化為貨幣值。 當您調用 ToString 將「C」格式說明符作為唯一參數的方法時,當前區域性 NumberFormatInfo 物件中的以下屬性值用於定義數值的字串表示形式:

此外,數位格式字串可能包含精度說明符。 此說明符的含義取決於使用它的格式字串,但它通常表示結果字元串中應出現的總位數或小數位數。 例如,以下示例使用 「X4」 標準數位字串和精度說明符創建具有四個十六進位數位的字串值。

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

有關標準數位格式字串的更多資訊,請參閱 標準數位格式字串

日期和時間值的標準格式字串是由特定 DateTimeFormatInfo 屬性存儲的自定義格式字串的別名。 例如,使用“D”格式說明符調用 ToString 日期和時間值的方法時,將使用存儲在當前區域性 DateTimeFormatInfo.LongDatePattern 屬性中的自定義格式字串來顯示日期和時間。 (有關自定義格式字串的更多資訊,請參閱 下一節。以下示例說明瞭這種關係。

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2009, 6, 30);
      Console.WriteLine($"D Format Specifier:     {date1:D}");
      string longPattern = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern;
      Console.WriteLine($"'{longPattern}' custom format string:     {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 Main0()
        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

有關標準日期和時間格式字串的更多資訊,請參閱 標準日期和時間格式字串

還可以使用標準格式字串來定義由物件 ToString(String) 的方法生成的應用程式定義物件的字串表示形式。 您可以定義物件支援的特定標準格式說明符,並且可以確定它們是區分大小寫還是不區分大小寫。 該方法的 ToString(String) 實現應支援以下內容:

  • 表示對象的習慣或常見格式的“G”格式說明符。 物件 ToString 方法的無參數重載應調用其 ToString(String) 重載,並向其傳遞“G”標準格式字串。

  • 支援等於 null 引用的格式說明符(Nothing 在 Visual Basic 中)。 等於 null 引用的格式說明符應被視為等效於 「G」 格式說明符。

例如,類 Temperature 可以在內部存儲以攝氏度為單位的溫度,並使用格式說明符以攝氏度、華氏度和開爾文為單位表示物件的值 Temperature 。 下列範例提供一個實例。

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 Example1
{
   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 Example1
    Public Sub Main1()
        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.

自訂格式字串

除了標準格式字串之外,.NET 還為數值以及日期和時間值定義自定義格式字串。 自定義格式字串由一個或多個自定義格式說明符組成,這些說明符定義值的字串表示形式。 例如,自定義日期和時間格式字串“yyyy/mm/dd hh:mm:ss.ffff t zzz”將日期轉換為 en-US 區域性格式為“2008/11/15 07:45:00.0000 P -08:00”形式的字符串表示形式。 同樣,自定義格式字串 「0000」 將整數值 12 轉換為 「0012」。 有關自訂格式字串的完整清單,請參閱 自定義日期和時間格式字元串自定義數位格式字串

如果格式字串由單個自定義格式說明符組成,則格式說明符前面應有百分號 (%) ,以避免與標準格式說明符混淆。 以下示例使用 「M」 自訂格式說明符來顯示特定日期月份的一位數或兩位數。

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 定義的自定義格式字串的別名。 自訂格式字串在為數值或日期和時間值提供應用程式定義的格式方面也提供了相當大的靈活性。 您可以通過將多個自定義格式說明符組合成一個自定義格式字串,為數值以及日期和時間值定義自己的自定義結果字串。 以下示例定義了一個自定義格式字串,該字串在月份名稱、日期和年份后的括號中顯示星期幾。

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 顯示為標準的 7 位數美國電話號碼及其區號。

using System;

public class Example17
{
   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 Example18
    Public Sub Main18()
        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

儘管標準格式字串通常可以處理應用程式定義類型的大多數格式設置需求,但您也可以定義自定義格式說明符來設置類型的格式。

設置字串和 .NET 類型的格式

所有數值類型(即 Byte、 、 DecimalDoubleInt16SByteSingleInt64UInt32UInt16BigIntegerUInt64Int32類型 ) 以及 DateTimeDateTimeOffset、 、 TimeSpanGuid和所有枚舉類型都支援使用格式字串進行格式設定。 有關每種類型支援的特定格式字串的資訊,請參閱以下主題:

標題 定義
標準數值格式字串 描述用於創建數值的常用字串表示形式的標準格式字串。
自訂數值格式字串 描述為數值創建特定於應用程式的格式的自訂格式字串。
標準日期和時間格式字串 描述用於創建和 DateTimeOffset 值的常用字串表示DateTime形式的標準格式字串。
自訂日期和時間格式字串 描述為 DateTimeDateTimeOffset 值創建特定於應用程式的格式的自訂格式字串。
標準 TimeSpan 格式字串 描述用於創建時間間隔的常用字串表示形式的標準格式字串。
自定義 TimeSpan 格式字串 描述為時間間隔創建特定於應用程式的格式的自定義格式字串。
列舉格式字串 描述用於創建枚舉值的字串表示形式的標準格式字串。
Guid.ToString(String) 描述值的標準 Guid 格式字串。

使用格式提供程式進行區分區域性的格式設置

儘管格式說明符允許您自定義物件的格式,但生成有意義的物件字串表示形式通常需要額外的格式資訊。 例如,使用“C”標準格式字串或自定義格式字串(如 “$ #,#.00”)將數位格式化為貨幣值時,至少需要有關正確貨幣符號、組分隔符和小數分隔符的資訊,以便包含在格式化字串中。 在 .NET 中,這些附加格式資訊通過 IFormatProvider 介面提供,該介面作為參數提供給數值類型和日期和時間類型的方法的一個或多個重載 ToStringIFormatProvider 在 .NET 中使用實現來支援特定於區域性的格式。 下面的示例說明了當使用表示不同區域性的三個 IFormatProvider 對象進行格式設置時,物件的字串表示形式如何變化。

using System;
using System.Globalization;

public class Example18
{
   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 Example11
    Public Sub Main11()
        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),該方法具有一個參數,該參數指定提供格式設置資訊的物件類型。 如果該方法可以提供該類型的物件,則返回該物件。 否則,它將返回 null 引用(Nothing 在 Visual Basic 中)。

IFormatProvider.GetFormat 是一個回調方法。 當您調用 ToString 包含 IFormatProvider 參數的方法重載時,它將調用 GetFormatIFormatProvider 物件的方法。 該方法 GetFormat 負責返回一個物件,該物件向該方法提供必要的格式資訊,如其 formatType 參數 ToString 所指定。

許多格式設置或字串轉換方法包括 type IFormatProvider為 parameter ,但在許多情況下,在調用該方法時,會忽略該參數的值。 下表列出了一些使用參數的格式設置方法以及它們傳遞給IFormatProvider.GetFormat該方法的物件類型Type

方法 formatType參數類型
ToString 數值類型的方法 System.Globalization.NumberFormatInfo
ToString 日期和時間類型的方法 System.Globalization.DateTimeFormatInfo
String.Format System.ICustomFormatter
StringBuilder.AppendFormat System.ICustomFormatter

備註

ToString數值類型和日期和時間類型的方法已重載,並且只有部分重載包含IFormatProvider參數。 如果方法沒有 type IFormatProvider的參數,則改為傳遞該屬性返回的物件 CultureInfo.CurrentCulture 。 例如,對 default Int32.ToString() 方法的調用最終會導致如下方法調用: Int32.ToString("G", System.Globalization.CultureInfo.CurrentCulture)

.NET 提供了三個實現 IFormatProvider

您還可以實現自己的格式提供程式來替換這些類中的任何一個。 但是,如果實現的方法 GetFormat 必須向 ToString 方法提供格式資訊,則它必須返回上表中列出的類型的物件。

數值的區分區域性的格式

默認情況下,數值的格式區分區域性。 如果在調用格式設置方法時未指定區域性,則使用當前區域性的格式約定。 下面的示例對此進行了說明,該示例將當前區域性更改四次,然後調用 Decimal.ToString(String) 該方法。 在每種情況下,結果字串都反映了當前區域性的格式約定。 這是因為 ToString and ToString(String) 方法包裝了對每個數值類型的 ToString(String, IFormatProvider) 方法的調用。

using System.Globalization;

public class Example6
{
   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 culture.
         CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName);
         Console.WriteLine($"The current culture is {CultureInfo.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

Module Example6
    Public Sub Main6()
        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 culture.
            CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName)
            Console.WriteLine($"The current culture is {CultureInfo.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 €

還可以通過調用具有provider參數的ToString重載並向其傳遞以下任一內容,為特定區域性設置數值的格式:

以下示例使用 NumberFormatInfo 表示英語 (美國) 和英語 (英國) 區域性以及法語和俄語非特定區域性的物件來設置浮點數的格式。

using System.Globalization;

public class Example7
{
    public static void Main()
    {
        double value = 1043.62957;
        string[] cultureNames = { "en-US", "en-GB", "ru", "fr" };

        foreach (string? 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 Example7
    Public Sub Main7()
        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

日期和時間值的區分區域性的格式

默認情況下,日期和時間值的格式是區分區域性的。 如果在調用格式設置方法時未指定區域性,則使用當前區域性的格式約定。 下面的示例對此進行了說明,該示例將當前區域性更改四次,然後調用 DateTime.ToString(String) 該方法。 在每種情況下,結果字串都反映了當前區域性的格式約定。 這是因為DateTime.ToString()、 、 DateTime.ToString(String)DateTimeOffset.ToString()DateTimeOffset.ToString(String) 方法包裝了對 和 DateTimeOffset.ToString(String, IFormatProvider) 方法的DateTime.ToString(String, IFormatProvider)調用。

using System.Globalization;

public class Example4
{
   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 culture.
         CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName);
         Console.WriteLine($"The current culture is {CultureInfo.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 Example4
    Public Sub Main4()
        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 culture.
            CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName)
            Console.WriteLine($"The current culture is {CultureInfo.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具有provider參數的 or DateTimeOffset.ToString 重載並向其傳遞以下任一內容來設置特定區域性的日期和時間值的格式:

以下範例使用 DateTimeFormatInfo 表示英語 (美國) 和英語 (英國) 區域性以及法語和俄語非特定區域性的物件來設置日期格式。

using System.Globalization;

public class Example5
{
   public static void Main()
   {
      DateTime dat1 = new(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($"{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 Example5
    Public Sub Main5()
        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($"{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 介面

通常,使用格式字串和IFormatProvider參數重載ToString方法的類型也會實現介面IFormattable。 此介面具有單個成員 ,該成員 IFormattable.ToString(String, IFormatProvider)包括格式字串和格式提供程式作為參數。

為應用程式定義的類實現 IFormattable 介面有兩個優點:

下面的示例定義實現 Temperature 介面的 IFormattable 類。 它支援使用“C”或“G”格式說明符來顯示以攝氏度為單位的溫度,使用“F”格式說明符來顯示以華氏度為單位的溫度,以及使用“K”格式說明符來顯示以開爾文為單位的溫度。

using System;
using System.Globalization;

namespace HotAndCold
{

    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));
            }
        }
    }
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 '{format}' format string is not supported."))
        End Select
    End Function
End Class

以下示例實例化一個 Temperature 物件。 然後, ToString 它調用該方法並使用多個複合格式字串來獲取物件的不同 Temperature 字串表示形式。 這些方法調用中的每一個反過來又調用 IFormattable 類的 Temperature 實現。

public class Example11
{
    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: {temp:K}");
        Console.WriteLine($"Temperature: {temp:F}");
        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 Example12
    Public Sub Main12()
        Dim temp As New Temperature(22D)
        CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US")
        Console.WriteLine(Convert.ToString(temp, New CultureInfo("ja-JP")))
        Console.WriteLine($"Temperature: {temp:K}")
        Console.WriteLine($"Temperature: {temp:F}")
        Console.WriteLine(String.Format(New CultureInfo("fr-FR"), $"Temperature: {temp:F}"))
    End Sub
End Module
' The example displays the following output:
'       22.00°C
'       Temperature: 295.15K
'       Temperature: 71.60°F
'       Temperature: 71,60°F

複合格式

某些方法(如 String.Format 和 ) StringBuilder.AppendFormat支援 複合格式。 複合格式字串是一種範本,它返回一個字串,該字串包含零個、一個或多個物件的字串表示形式。 每個物件在複合格式字串中都由一個索引格式項表示。 格式項的索引對應於它在方法的參數清單中表示的物件的位置。 索引從零開始。 例如,在以下對 String.Format 該方法的調用中,第一個格式項 {0:D}, 被替換為 的字串表示 thatDate形式;第二個格式項 {1}被替換為 的字串表示 item1形式;第三個格式項 {2:C2}被 的字串表示 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.

除了將格式項替換為其相應物件的字串表示形式之外,格式項還允許您控制以下內容:

  • 物件表示為字串的特定方式(如果對象實現 IFormattable 介面並支援格式字串)。 為此,您可以在格式項的索引後面加上一個 : (冒號),後跟一個有效的格式字串。 前面的示例通過使用 「d」 (短日期模式) 格式字串(例如, {0:d})設置日期值的格式,並使用 「C2」 格式字串(例如 {2:C2})設置數值的格式,以將數位表示為具有兩個小數十進位數位的貨幣值。

  • 包含物件的字串表示形式的欄位的寬度,以及該欄位中字串表示形式的對齊方式。 為此,您可以在格式項的索引後面加上 , (逗號) 後跟字段 width。 如果欄位寬度為正值,則字串在欄位中右對齊,如果欄位寬度為負值,則字串在欄位中左對齊。 以下示例將 20 個字元欄位中的日期值左對齊,並將十進位值與 11 個字元欄位中的一個小數位右對齊。

    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}

有關複合格式的更多資訊,請參閱複合格式。

使用 ICustomFormatter 進行自定義格式設置

兩種複合格式設置方法 String.Format(IFormatProvider, String, Object[])StringBuilder.AppendFormat(IFormatProvider, String, Object[])包括支援自定義格式設置的格式提供程序參數。 當調用這些格式設置方法中的任何一個時,它會傳遞一個Type物件,該物件表示格式提供程式GetFormat方法的ICustomFormatter介面。 然後,該方法 GetFormat 負責返回 ICustomFormatter 提供自定義格式的實現。

ICustomFormatter 介面具有單個方法 Format(String, Object, IFormatProvider),該方法由複合格式設置方法自動調用,對複合格式字串中的每個格式項調用一次。 該方法 Format(String, Object, IFormatProvider) 有三個參數:格式字串(表示 formatString 格式項中的參數)、要格式化的物件和 IFormatProvider 提供格式設置服務的物件。 通常,實現 ICustomFormatter 的類也實現 , IFormatProvider因此最後一個參數是對自定義格式設置類本身的引用。 該方法返回要格式化的物件的自定義格式化字串表示形式。 如果該方法無法設置物件的格式,則應返回 null 引用(Nothing 在 Visual Basic 中)。

以下示例提供了一個 ICustomFormatter 名為的 ByteByByteFormatter 實現,該實現將整數值顯示為兩位數十六進位值序列,後跟一個空格。

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 is not null) && !formatProvider.Equals(this)) return "";

        // Handle only hexadecimal format string.
        if ((format is not null) && !format.StartsWith("X")) return "";

        byte[] bytes;

        // Handle only integral types.
        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 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 "";

        string output= "";
        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 類來格式化整數值。 請注意,在第二個String.Format(IFormatProvider, String, Object[])方法調用中多次調用該方法ICustomFormatter.Format,並且在第三個方法調用中使用預設NumberFormatInfo提供程式,因為 . ByteByByteFormatter.Format 方法無法識別 「N0」 格式字串並返回 null 引用(Nothing 在 Visual Basic 中)。

public class Example10
{
    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 Example10
    Public Sub Main10()
        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

另請參閱

標題 定義
標準數值格式字串 描述用於創建數值的常用字串表示形式的標準格式字串。
自訂數值格式字串 描述為數值創建特定於應用程式的格式的自訂格式字串。
標準日期和時間格式字串 描述用於創建值的常用字串表示 DateTime 形式的標準格式字串。
自訂日期和時間格式字串 描述為值創建特定於應用程式的格式 DateTime 的自訂格式字串。
標準 TimeSpan 格式字串 描述用於創建時間間隔的常用字串表示形式的標準格式字串。
自定義 TimeSpan 格式字串 描述為時間間隔創建特定於應用程式的格式的自定義格式字串。
列舉格式字串 描述用於創建枚舉值的字串表示形式的標準格式字串。
複合格式設定 介紹如何在字串中嵌入一個或多個格式化值。 該字串隨後可以顯示在控制臺上或寫入流中。
剖析字串 描述如何將物件初始化為這些物件的字串表示形式所描述的值。 解析是格式化的逆運算。

參考文獻