Share via


複合格式

.NET Framework 複合格式功能會採用物件清單和複合格式字串做為輸入。 複合格式字串是由混合索引替代符號 (Placeholder) 的固定文字所組成 (這些符號稱為對應至清單內物件的格式項目)。 格式作業產生的結果字串是由原始固定文字所組成,這些固定文字混合了清單中代表物件的字串。

類似 FormatAppendFormat 的方法及 WriteLineTextWriter.WriteLine 的某些多載可支援複合格式功能。 String.Format 方法會產生格式化結果字串,而 AppendFormat 方法會將格式化結果字串附加到 StringBuilder 物件上,Console.WriteLine 方法則會將格式化結果字串顯示到主控台 (Console),而 TextWriter.WriteLine 方法會將格式化結果字串寫入資料流或檔案。

複合格式字串

複合格式字串和物件清單會當做支援複合格式功能之方法的引數來使用。 複合格式字串是由零個或更多段與一個或多個格式項目混合的固定文字所組成, 固定文字是您選擇的任何文字,而每個格式項目都會對應到清單內的一個物件或 boxed 結構。 複合格式功能將會傳回新的結果字串,其中每一個格式項目都會由清單內對應物件的字串表示來取代。

請考量下列 Format 程式碼片段。

Dim myName As String = "Fred"
String.Format("Name = {0}, hours = {1:hh}", myName, DateTime.Now)
string myName = "Fred";
String.Format("Name = {0}, hours = {1:hh}", myName, DateTime.Now);

固定的文字為 "Name = " 和 ", hours = "。 格式項目為 "{0}" (其索引為 0,且會對應至物件 myName) 及 "{1:hh}" (其索引為 1,且會對應至物件 DateTime.Now)。

格式項目語法

每個格式項目都會使用下列格式,並由下列元件所組成:

{index[,alignment][:formatString]}

成對的大括號 ("{" 和 "}") 是必要的。

索引元件

強制的 index 元件 (也稱為參數規範) 是用以識別物件清單中對應項目的數字 (從 0 開始)。 也就是說,參數規範為 0 的格式項目會格式化清單中的第一個物件,而參數規範為 1 的格式項目會格式化清單中的第二個物件,依此類推。

多個格式項目可以藉由指定相同參數規範來參考物件清單中的相同項目。 例如,您可以指定複合格式字串 (如:"{0:X} {0:E} {0:N}") 來格式化十六進位、科學格式和數字格式的相同數值。

每個格式項目皆可參考清單內的任何物件。 例如,如果有三個物件,您可以指定複合格式字串 (如:"{1} {0} {2}") 來格式化第二個、第一個和第三個物件。 不是格式項目所參考的物件會被忽略。 如果參數規範指派超出物件清單範圍的項目,即會產生執行階段例外狀況。

對齊元件

選擇性 alignment 元件為帶正負號的整數 (Signed Integer),它指示慣用的格式化欄位寬度。 如果 alignment 的值小於格式化字串的長度,alignment 會被忽略而使用格式化字串的長度當做欄位寬度。 如果 alignment 為正數,欄位中的格式化資料會靠右對齊;如果 alignment 為負數,則會靠左對齊。 如果填補有必要,則會使用泛空白字元 (White Space)。 如果指定了 alignment,逗號即是必須的。

格式字串元件

選擇性的 formatString 元件是一個格式字串,適用於將格式化的物件型別。 如果對應的物件為數值,請指定標準或自訂數值格式字串;如果對應的物件為 DateTime 物件,請指定標準或自訂日期和時間格式字串;或者,如果對應的物件為列舉值,請指定列舉格式字串。 如果未指定 formatString,則會使用數值、日期和時間或列舉型別的一般 ("G") 格式規範。 如果指定 formatString,則需要冒號。

注意事項注意事項

如需標準和自訂數值格式字串的清單,請參閱標準數值格式字串自訂數值格式字串。如需標準日期和時間格式字串的清單,請參閱標準日期和時間格式字串自訂日期和時間格式字串

逸出大括號

左右大括號會被解譯成格式項目的開頭與結尾。 因此,您必須使用逸出序列 (Escape Sequence),才能顯示字面上的左右大括號。 請在固定文字中指定兩個左邊的大括號 ("{{"),以顯示一個左邊的大括號 ("{"),或者指定兩個右邊的大括號 ("}}") 來顯示一個右邊的大括號 ("}")。 格式項目中的括號會以它們出現的順序依序解譯, 但是不支援解譯巢狀大括號。

解譯逸出括號的方式,可能會造成無法預期的結果。 例如,格式項目 "{{{0:D}}}" 原本是要顯示一個左邊大括號、一個格式化為十進位的數值和一個右邊大括號。 然而,格式項目實際會以下列方式來解譯:

  1. 前面兩個左邊大括號 ("{{") 逸出,產生一個左邊大括號。

  2. 接下來的三個字元 ("{0:") 會解譯成格式項目的開頭。

  3. 再下一個字元 ("D") 可能解譯成十進位 (Decimal) 標準數值格式規範,但後面兩個逸出的右邊大括號 ("}}") 會產生一個大括號。 由於結果字串 ("D}") 並非標準的數值格式規範,因此,結果字串會被解譯成自訂格式字串,表示會顯示成常值字串 "D}"。

  4. 最後的大括號 ("}") 會被解譯成格式項目的結尾。

  5. 最後顯示的結果會是常值字串 "{D}", 而要進行格式化的數值則不會顯示出來。

撰寫程式碼時,能夠避免錯誤解譯逸出大括號和格式項目的方法,就是個別地格式化大括號和格式項目。 也就是說,在第一個格式化作業中顯示常值的左邊大括號,在下一個作業中顯示格式項目的結果,接著在最終作業中顯示常值的右邊大括號。 下列範示範這個方法。

Dim value As Integer = 6324
Dim output As String = String.Format("{0}{1:D}{2}", _
                                     "{", value, "}")
Console.WriteLine(output)   
' The example displays the following output:
'       {6324}
int value = 6324;
string output = string.Format("{0}{1:D}{2}", 
                             "{", value, "}");
Console.WriteLine(output);
// The example displays the following output:
//       {6324}                            

處理順序

參數清單中每個對應至格式項目的值都會藉由執行下列清單中的步驟,而轉換為字串。 如果在前三個步驟中有任何條件成立,則會在該步驟傳回值的字串表示,而不會再執行後續步驟。

  1. 如果要格式化的值是 null,則會傳回空字串 ("")。

  2. 如果複合格式方法包含 IFormatProvider 型別 (這個型別同樣會實作 ICustomFormatter 介面) 的參數,則會將值傳遞給 ICustomFormatter.Format 方法。

  3. 如果值實作 IFormattable 介面,則會呼叫其 IFormattable.ToString 方法。

  4. 呼叫型別的 ToString 方法,該方法是由 Object 類別覆寫或是繼承自該類別。

對齊會在已經執行前面的步驟之後套用。

程式碼範例

下列範例顯示一個使用複合格式建立的字串,以及另一個使用物件的 ToString 方法建立的字串。 這兩個型別的格式化產生相等結果。

Dim FormatString1 As String = String.Format("{0:dddd MMMM}", DateTime.Now)
Dim FormatString2 As String = DateTime.Now.ToString("dddd MMMM") 
string FormatString1 = String.Format("{0:dddd MMMM}", DateTime.Now);
string FormatString2 = DateTime.Now.ToString("dddd MMMM");

假設目前日期是五月份的星期四,則前面範例中兩個字串的值在美國英文文化特性中都是 Thursday May 。

Console.WriteLine 會公開與 String.Format 相同的功能。 這兩種方法唯一的差別在於,String.Format 會以字串形式傳回結果,而 Console.WriteLine 則會將結果寫入至與 Console 物件關聯的輸出資料流。 下列範例使用 Console.WriteLine 方法,將 MyInt 的值格式化為貨幣值。

Dim MyInt As Integer = 100
Console.WriteLine("{0:C}", MyInt)
' The example displays the following output
' if en-US is the current culture:
'        $100.00
int MyInt = 100;
Console.WriteLine("{0:C}", MyInt);
// The example displays the following output 
// if en-US is the current culture:
//        $100.00

下列範例示範多個物件的格式化,其中包括使用兩種不同方式來格式化一個物件。

Dim myName As String = "Fred"
Console.WriteLine(String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}", _
                  myName, DateTime.Now))
' Depending on the current time, the example displays output like the following:
'    Name = Fred, hours = 11, minutes = 30                 
string myName = "Fred";
Console.WriteLine(String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}",
      myName, DateTime.Now));
// Depending on the current time, the example displays output like the following:
//    Name = Fred, hours = 11, minutes = 30                 

下列範例示範格式設定中的對齊用法。 格式化的引數會放在兩個垂直線 (|) 字元之間以強調所產生的對齊。

Dim myFName As String = "Fred"
Dim myLName As String = "Opals"

Dim myInt As Integer = 100
Dim FormatFName As String = String.Format("First Name = |{0,10}|", myFName)
Dim FormatLName As String = String.Format("Last Name = |{0,10}|", myLName)
Dim FormatPrice As String = String.Format("Price = |{0,10:C}|", myInt)
Console.WriteLine(FormatFName)
Console.WriteLine(FormatLName)
Console.WriteLine(FormatPrice)
Console.WriteLine()

FormatFName = String.Format("First Name = |{0,-10}|", myFName)
FormatLName = String.Format("Last Name = |{0,-10}|", myLName)
FormatPrice = String.Format("Price = |{0,-10:C}|", myInt)
Console.WriteLine(FormatFName)
Console.WriteLine(FormatLName)
Console.WriteLine(FormatPrice)
' The example displays the following output on a system whose current
' culture is en-US:
'          First Name = |      Fred|
'          Last Name = |     Opals|
'          Price = |   $100.00|
'
'          First Name = |Fred      |
'          Last Name = |Opals     |
'          Price = |$100.00   |
string myFName = "Fred";
string myLName = "Opals";
int myInt = 100;
string FormatFName = String.Format("First Name = |{0,10}|", myFName);
string FormatLName = String.Format("Last Name = |{0,10}|", myLName);
string FormatPrice = String.Format("Price = |{0,10:C}|", myInt); 
Console.WriteLine(FormatFName);
Console.WriteLine(FormatLName);
Console.WriteLine(FormatPrice);
Console.WriteLine();

FormatFName = String.Format("First Name = |{0,-10}|", myFName);
FormatLName = String.Format("Last Name = |{0,-10}|", myLName);
FormatPrice = String.Format("Price = |{0,-10:C}|", myInt);
Console.WriteLine(FormatFName);
Console.WriteLine(FormatLName);
Console.WriteLine(FormatPrice);
// The example displays the following output on a system whose current
// culture is en-US:
//          First Name = |      Fred|
//          Last Name = |     Opals|
//          Price = |   $100.00|
//
//          First Name = |Fred      |
//          Last Name = |Opals     |
//          Price = |$100.00   |

請參閱

參考

WriteLine

String.Format

概念

格式化型別

標準數值格式字串

自訂數值格式字串

標準日期和時間格式字串

自訂日期和時間格式字串

列舉型別格式字串

其他資源

標準 TimeSpan 格式字串

自訂 TimeSpan 格式字串