String.Format 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
根據指定的格式將物件的值轉換為字串,並將它們插入到另一個字串。
如果您不熟悉 String.Format
方法,請參閱 String.Format 方法入門一節以取得快速概觀。
如需 String.Format
方法的一般文件,請參閱備註一節。
多載
Format(String, Object) |
以指定物件的字串表示,取代字串中的一或多個格式項目。 |
Format(String, Object[]) |
以指定陣列中對應物件的字串表示,取代指定之字串中的格式項目。 |
Format(IFormatProvider, String, Object) |
以對應物件的字串表示,取代指定之字串中的一或多個格式項目。 參數提供特定文化特性格式資訊。 |
Format(IFormatProvider, String, Object[]) |
以指定陣列中對應物件的字串表示,取代字串中的格式項目。 參數提供特定文化特性格式資訊。 |
Format(String, Object, Object) |
以兩個指定物件的字串表示,取代字串中的格式項目。 |
Format(IFormatProvider, String, Object, Object) |
以兩個指定物件的字串表示,取代字串中的格式項目。 參數提供特定文化特性格式資訊。 |
Format(String, Object, Object, Object) |
以三個指定物件的字串表示,取代字串中的格式項目。 |
Format(IFormatProvider, String, Object, Object, Object) |
以三個指定物件的字串表示,取代字串中的格式項目。 參數提供特定文化特性格式資訊。 |
範例
許多呼叫方法的範例 Format 都是透過本文的「 備註 」一節來進行。
您也可以下載一組完整的 String.Format
範例,其中包含 適用于 c # 的 .net Core 專案。
以下是本文中包含的一些範例:
建立格式字串
控制格式化的輸出
控制格式
控制間距
控制對齊
控制整數數位的數目
控制小數分隔符號之後的位數
在結果字串中包含常值大括弧
使格式字串區分文化特性
自訂格式化操作
備註
重要
請不要呼叫 String.Format 方法或使用 複合格式字串,您可以使用「內插字串」(如果您的語言支援它們的話)。 內插字串是包含「插入運算式」的字串。 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。 如需詳細資訊,請參閱內插字串 (C# 參考) 和內插字串 (Visual Basic 參考)。
本節內容:
開始使用字串格式方法
我會呼叫何種方法?
格式方法簡介
格式專案
如何格式化引數
格式化具有相同索引的專案
格式設定和文化特性
自訂格式化作業
字串。格式 Q & A
開始使用字串格式方法
String.Format如果您需要將物件、變數或運算式的值插入至另一個字串,請使用。 例如,您可以將值的值插入 Decimal 字串,以單一字串的形式顯示給使用者:
Decimal pricePerOunce = (Decimal)17.36;
String^ s = String::Format("The current price is {0} per ounce.",
pricePerOunce);
// Result: The current price is 17.36 per ounce.
Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0} per ounce.",
pricePerOunce);
Console.WriteLine(s);
// Result: The current price is 17.36 per ounce.
Dim pricePerOunce As Decimal = 17.36d
Dim s As String = String.Format("The current price is {0} per ounce.",
pricePerOunce)
' Result: The current price is 17.36 per ounce.
您可以控制該值的格式:
Decimal pricePerOunce = (Decimal)17.36;
String^ s = String::Format("The current price is {0:C2} per ounce.",
pricePerOunce);
// Result if current culture is en-US:
// The current price is $17.36 per ounce.
Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0:C2} per ounce.",
pricePerOunce);
Console.WriteLine(s);
// Result if current culture is en-US:
// The current price is $17.36 per ounce.
Dim pricePerOunce As Decimal = 17.36d
Dim s As String = String.Format("The current price is {0:C2} per ounce.",
pricePerOunce)
' Result if current culture is en-US:
' The current price is $17.36 per ounce.
除了格式之外,您也可以控制對齊和間距。
插入字串
String.Format 以格式字串開頭,後面接著一或多個將轉換成字串並插入格式字串中指定位置的物件或運算式。 例如:
Decimal temp = (Decimal)20.4;
String^ s = String::Format("The temperature is {0}°C.", temp);
Console::WriteLine(s);
// Displays 'The temperature is 20.4°C.'
decimal temp = 20.4m;
string s = String.Format("The temperature is {0}°C.", temp);
Console.WriteLine(s);
// Displays 'The temperature is 20.4°C.'
Dim temp As Decimal = 20.4d
Dim s As String = String.Format("The temperature is {0}°C.", temp)
Console.WriteLine(s)
' Displays 'The temperature is 20.4°C.'
{0}
格式字串中的是格式專案。 0
這是將在該位置插入其字串值的物件索引。 (索引從0開始 ) 。如果要插入的物件不是字串,則會呼叫它的方法,將它 ToString
轉換成一個字串,然後再將它插入結果字串中。
以下是在物件清單中使用兩個格式專案和兩個物件的另一個範例:
String^ s = String::Format("At {0}, the temperature is {1}°C.",
DateTime::Now, 20.4);
// Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
string s = String.Format("At {0}, the temperature is {1}°C.",
DateTime.Now, 20.4);
Console.WriteLine(s);
// Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
Dim s As String = String.Format("At {0}, the temperature is {1}°C.",
Date.Now, 20.4)
' Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
只要每個格式專案的索引在物件清單中都有相符的物件,您就可以在物件清單中擁有任意數量的格式專案和任意數量的物件。 您也不需要擔心您呼叫的多載;編譯器會為您選取適當的一個。
控制項格式
您可以在格式專案中的索引後面加上格式字串,以控制物件的格式化方式。 例如, {0:d}
將 "d" 格式字串套用至物件清單中的第一個物件。 以下是具有單一物件和兩個格式專案的範例:
String^ s = String::Format("It is now {0:d} at {0:t}",
DateTime::Now);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
string s = String.Format("It is now {0:d} at {0:t}", DateTime.Now);
Console.WriteLine(s);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
Dim s As String = String.Format("It is now {0:d} at {0:t}",
Date.Now)
' Output similar to: 'It is now 4/10/2015 at 10:04 AM'
許多類型都支援格式字串,包括標準和自訂格式) 字串 (的所有數數值型別、標準和自訂格式字串的所有日期和時間 (標準和自訂格式字串) 和時間間隔 (標準和自訂格式字串) 、所有列舉類型的列舉類型,以及guid。 您也可以將格式字串的支援新增至您自己的類型。
控制項間距
您可以使用會 {0,12}
插入12個字元字串的語法,來定義插入結果字串中的字串寬度。 在此情況下,第一個物件的字串表示會在12個字元的欄位中靠右對齊。 (如果第一個物件的字串表示長度超過12個字元,則會忽略慣用的欄位寬度,並將整個字串插入結果字串中。 )
下列範例會定義6個字元的欄位來保存字串 "Year" 和一些年份字串,以及一個15個字元的欄位來保存字串「人口」和一些人口資料。 請注意,字元在欄位中是靠右對齊。
array<int>^ years = { 2013, 2014, 2015 };
array<int>^ population = { 1025632, 1105967, 1148203 };
StringBuiler^ sb = gcnew StringBuilder();
sb->Append(String::Format("{0,6} {1,15}\n\n", "Year", "Population"));
for(int index = 0; index < years->Length; index++)
sb->AppendFormat("{0,6} {1,15:N0}\n",
years[index], population[index]);
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
int[] years = { 2013, 2014, 2015 };
int[] population = { 1025632, 1105967, 1148203 };
var sb = new System.Text.StringBuilder();
sb.Append(String.Format("{0,6} {1,15}\n\n", "Year", "Population"));
for (int index = 0; index < years.Length; index++)
sb.Append(String.Format("{0,6} {1,15:N0}\n", years[index], population[index]));
Console.WriteLine(sb);
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
Dim years() As Integer = { 2013, 2014, 2015 }
Dim population() As Integer = { 1025632, 1105967, 1148203 }
Dim sb As New StringBuilder()
sb.Append(String.Format("{0,6} {1,15}{2}{2}",
"Year", "Population", vbCrLf))
For index As Integer = 0 To years.Length - 1
sb.AppendFormat("{0,6} {1,15:N0}{2}",
years(index), population(index), vbCrLf)
Next
' Result:
' Year Population
'
' 2013 1,025,632
' 2014 1,105,967
' 2015 1,148,203
控制項對齊
依預設,如果您指定欄位寬度,字串就會在其欄位中靠右對齊。 若要在欄位中靠左對齊字串,您可以在欄位寬度前面加上負號,例如 {0,-12}
定義12個字元的左對齊欄位。
下列範例與上一個範例類似,不同之處在于它會將標籤和資料靠左對齊。
array<int>^ years = { 2013, 2014, 2015 };
array<int>^ population = { 1025632, 1105967, 1148203 };
String^ s = String::Format("{0,-10} {1,-10}\n\n", "Year", "Population");
for(int index = 0; index < years->Length; index++)
s += String::Format("{0,-10} {1,-10:N0}\n",
years[index], population[index]);
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
int[] years = { 2013, 2014, 2015 };
int[] population = { 1025632, 1105967, 1148203 };
String s = String.Format("{0,-10} {1,-10}\n\n", "Year", "Population");
for(int index = 0; index < years.Length; index++)
s += String.Format("{0,-10} {1,-10:N0}\n",
years[index], population[index]);
Console.WriteLine($"\n{s}");
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
Dim years() As Integer = { 2013, 2014, 2015 }
Dim population() As Integer = { 1025632, 1105967, 1148203 }
Dim s As String = String.Format("{0,-10} {1,-10}{2}{2}",
"Year", "Population", vbCrLf)
For index As Integer = 0 To years.Length - 1
s += String.Format("{0,-10} {1,-10:N0}{2}",
years(index), population(index), vbCrLf)
Next
' Result:
' Year Population
'
' 2013 1,025,632
' 2014 1,105,967
' 2015 1,148,203
String.Format 利用複合格式功能。 如需詳細資訊,請參閱複合格式設定。
我會呼叫何種方法?
收件者 | 呼叫 |
---|---|
使用目前文化特性的慣例來格式化一或多個物件。 | 除了包含參數的多載之外 provider ,其餘的多載也會 Format 包含一個 String 參數,後面接著一個或多個物件參數。 因此,您不需要判斷 Format 您想要呼叫的多載。 您的語言編譯器會 provider 根據您的引數清單,從沒有參數的多載中選取適當的多載。 例如,如果您的引數清單有五個引數,則編譯器會呼叫 Format(String, Object[]) 方法。 |
使用特定文化特性的慣例來格式化一或多個物件。 | 以參數開頭的每個多載 Format provider 後面都會接著一個 String 參數和一個或多個物件參數。 因此,您不需要判斷 Format 您想要呼叫的特定多載。 您的語言編譯器會 provider 根據您的引數清單,從具有參數的多載中選取適當的多載。 例如,如果您的引數清單有五個引數,則編譯器會呼叫 Format(IFormatProvider, String, Object[]) 方法。 |
執行自訂格式作業,方法是執行 ICustomFormatter 或 IFormattable 實作為。 | 具有參數之四個多載的任一個 provider 。 編譯器會 provider 根據您的引數清單,從具有參數的多載中選取適當的多載。 |
格式方法簡介
方法的每個多載都會 Format 使用 複合格式功能 ,在複合格式字串中包含以零為基底的索引預留位置,稱為 格式專案。 在執行時間,每個格式專案都會取代為參數清單中對應引數的字串表示。 如果引數的值為 null
,則會以取代格式專案 String.Empty 。 例如,下列 Format(String, Object, Object, Object) 方法呼叫包括具有三個格式專案的格式字串:、 {0} {1} 和 {2} ,以及具有三個專案的引數清單。
using namespace System;
void main()
{
DateTime^ dat = gcnew DateTime(2012, 1, 17, 9, 30, 0);
String^ city = "Chicago";
int temp = -16;
String^ output = String::Format("At {0} in {1}, the temperature was {2} degrees.",
dat, city, temp);
Console::WriteLine(output);
}
// The example displays the following output:
// At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0);
string city = "Chicago";
int temp = -16;
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.",
dat, city, temp);
Console.WriteLine(output);
// The example displays output like the following:
// At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
Dim dat As Date = #1/17/2012 9:30AM#
Dim city As String = "Chicago"
Dim temp As Integer = -16
Dim output As String = String.Format("At {0} in {1}, the temperature was {2} degrees.",
dat, city, temp)
Console.WriteLine(output)
' The example displays the following output:
' At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
格式專案
格式專案具有下列語法:
{index[,alignment][:formatString]}
括弧表示選擇性元素。 需要左括弧和右大括弧。 (在格式字串中加入常值的開頭或結尾大括弧,請參閱複合格式一文中的「轉義大括弧」一節。 )
例如,格式化貨幣值的格式專案可能會如下所示:
String::Format("{0,-10:C}", (Decimal) 126347.89);
var value = String.Format("{0,-10:C}", 126347.89m);
Console.WriteLine(value);
String.Format("{0,-10:C}", 126347.89d)
格式專案具有下列元素:
指數
引數以零為起始的索引,其字串表示會包含在字串中的這個位置。 如果這個引數為 null
,字串中的這個位置將會包含空字串。
對準
選擇性。 帶正負號的整數,表示插入引數之欄位的總長度,以及它是否靠右對齊 (正整數) 或靠左對齊 (負整數) 。 如果您省略 對齊,則會將對應引數的字串表示插入不含前置或尾端空格的欄位中。
如果 對齊 的值小於要插入的引數長度,則會忽略 對齊 ,並使用引數的字串表示長度作為欄位寬度。
字串
選擇性。 字串,指定對應引數結果字串的格式。 如果您省略 格式 字串,則會呼叫對應的引數的無參數 ToString
方法,以產生其字串表示。 如果您指定了格式 字串,則格式專案所參考的引數必須執行 IFormattable 介面。 支援格式字串的類型包括:
DateTime 和 DateTimeOffset。 (查看 標準日期和時間格式字串 ,以及 自訂日期和時間格式字串。 )
所有列舉類型。 (請參閱 列舉格式字串。 )
TimeSpan 值。 (參閱 標準 Timespan 格式字串 和 自訂 timespan 格式字串。 )
GUID。 (查看 Guid.ToString(String) 方法。 )
不過,請注意,任何自訂類型都可以 IFormattable 實作為或擴充現有的型別 IFormattable 。
下列範例會使用 alignment
和 formatString
引數來產生格式化輸出。
using namespace System;
void main()
{
// Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
array<Tuple<String^, DateTime, int, DateTime, int>^>^ cities = gcnew array<Tuple<String^, DateTime, int, DateTime, int>^>
{ gcnew Tuple<String^, DateTime, int, DateTime, int>("Los Angeles", DateTime(1940, 1, 1), 1504277,
DateTime(1950, 1, 1), 1970358),
gcnew Tuple<String^, DateTime, int, DateTime, int>("New York", DateTime(1940, 1, 1), 7454995,
DateTime(1950, 1, 1), 7891957),
gcnew Tuple<String^, DateTime, int, DateTime, int>("Chicago", DateTime(1940, 1, 1), 3396808,
DateTime(1950, 1, 1), 3620962),
gcnew Tuple<String^, DateTime, int, DateTime, int>("Detroit", DateTime(1940, 1, 1), 1623452,
DateTime(1950, 1, 1), 1849568) };
// Display header
String^ header = String::Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
"City", "Year", "Population", "Change (%)");
Console::WriteLine(header);
String^ output;
for each (Tuple<String^, DateTime, int, DateTime, int>^ city in cities) {
output = String::Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
city->Item1, city->Item2, city->Item3, city->Item4, city->Item5,
(city->Item5 - city->Item3)/ (double)city->Item3);
Console::WriteLine(output);
}
}
// The example displays the following output:
// City Year Population Year Population Change (%)
//
// Los Angeles 1940 1,504,277 1950 1,970,358 31.0 %
// New York 1940 7,454,995 1950 7,891,957 5.9 %
// Chicago 1940 3,396,808 1950 3,620,962 6.6 %
// Detroit 1940 1,623,452 1950 1,849,568 13.9 %
// Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
Tuple<string, DateTime, int, DateTime, int>[] cities =
{ Tuple.Create("Los Angeles", new DateTime(1940, 1, 1), 1504277,
new DateTime(1950, 1, 1), 1970358),
Tuple.Create("New York", new DateTime(1940, 1, 1), 7454995,
new DateTime(1950, 1, 1), 7891957),
Tuple.Create("Chicago", new DateTime(1940, 1, 1), 3396808,
new DateTime(1950, 1, 1), 3620962),
Tuple.Create("Detroit", new DateTime(1940, 1, 1), 1623452,
new DateTime(1950, 1, 1), 1849568) };
// Display header
var header = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
"City", "Year", "Population", "Change (%)");
Console.WriteLine(header);
foreach (var city in cities) {
var output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
(city.Item5 - city.Item3)/ (double)city.Item3);
Console.WriteLine(output);
}
// The example displays the following output:
// City Year Population Year Population Change (%)
//
// Los Angeles 1940 1,504,277 1950 1,970,358 31.0 %
// New York 1940 7,454,995 1950 7,891,957 5.9 %
// Chicago 1940 3,396,808 1950 3,620,962 6.6 %
// Detroit 1940 1,623,452 1950 1,849,568 13.9 %
Module Example
Public Sub Main()
' Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
Dim cities() = _
{ Tuple.Create("Los Angeles", #1/1/1940#, 1504277, #1/1/1950#, 1970358),
Tuple.Create("New York", #1/1/1940#, 7454995, #1/1/1950#, 7891957),
Tuple.Create("Chicago", #1/1/1940#, 3396808, #1/1/1950#, 3620962),
Tuple.Create("Detroit", #1/1/1940#, 1623452, #1/1/1950#, 1849568) }
' Display header
Dim header As String = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}",
"City", "Year", "Population", "Change (%)")
Console.WriteLine(header)
Console.WriteLine()
For Each city In cities
Dim output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
(city.Item5 - city.Item3)/city.Item3)
Console.WriteLine(output)
Next
End Sub
End Module
' The example displays the following output:
' City Year Population Year Population Change (%)
'
' Los Angeles 1940 1,504,277 1950 1,970,358 31.0 %
' New York 1940 7,454,995 1950 7,891,957 5.9 %
' Chicago 1940 3,396,808 1950 3,620,962 6.6 %
' Detroit 1940 1,623,452 1950 1,849,568 13.9 %
如何格式化引數
格式專案會依序從字串開頭開始處理。 每個格式專案都有對應至方法引數清單中之物件的索引。 方法會抓取自 Format 變數,並衍生其字串表示,如下所示:
如果引數為
null
,則方法會插入 String.Empty 結果字串中。 您不必擔心如何處理 NullReferenceException null 引數。如果您呼叫多載, Format(IFormatProvider, String, Object[]) 而
provider
物件的 IFormatProvider.GetFormat 實值傳回非 null 的 ICustomFormatter 實值,則會將引數傳遞給它的 ICustomFormatter.Format(String, Object, IFormatProvider) 方法。 如果格式專案包含格式 字串 引數,則會將它做為第一個引數傳遞給方法。 如果 ICustomFormatter 可以使用此執行並產生非 null 字串,則會以引數的字串表示傳回該字串; 否則,會執行下一個步驟。如果引數實作為 IFormattable 介面, IFormattable.ToString 則會呼叫其實作為。
引數的無參數
ToString
方法(覆寫或繼承自基底類別的實作為)稱為。
如需攔截方法呼叫的範例, ICustomFormatter.Format 並可讓您查看 Format 方法針對複合格式字串中的每個格式專案傳遞至格式化方法的資訊,請參閱 範例:攔截提供者和羅馬數字格式器。
格式化具有相同索引的專案
Format FormatException 如果索引項目的索引大於或等於引數清單中的引數數目,則方法會擲回例外狀況。 不過, format
只要有多個格式專案具有相同的索引,就可以包含比引數更多的格式專案。 在下列範例中的 Format(String, Object) 方法呼叫中,引數清單具有單一引數,但格式字串包含兩個格式專案:一個會顯示數位的十進位值,另一個則會顯示其十六進位值。
short[] values= { Int16.MinValue, -27, 0, 1042, Int16.MaxValue };
Console.WriteLine("{0,10} {1,10}\n", "Decimal", "Hex");
foreach (short value in values)
{
string formatString = String.Format("{0,10:G}: {0,10:X}", value);
Console.WriteLine(formatString);
}
// The example displays the following output:
// Decimal Hex
//
// -32768: 8000
// -27: FFE5
// 0: 0
// 1042: 412
// 32767: 7FFF
Module Example
Public Sub Main()
Dim values() As Short = { Int16.MinValue, -27, 0, 1042, Int16.MaxValue }
Console.WriteLine("{0,10} {1,10}", "Decimal", "Hex")
Console.WriteLine()
For Each value As Short In values
Dim formatString As String = String.Format("{0,10:G}: {0,10:X}", value)
Console.WriteLine(formatString)
Next
End Sub
End Module
' The example displays the following output:
' Decimal Hex
'
' -32768: 8000
' -27: FFE5
' 0: 0
' 1042: 412
' 32767: 7FFF
格式和文化特性
一般而言,引數清單中的物件會使用目前文化特性的慣例(由屬性傳回),轉換為其字串表示 CultureInfo.CurrentCulture 。 您可以藉由呼叫其中一個包含參數的多載,來控制這項行為 Format provider
。 provider
參數是一種 IFormatProvider 可提供自訂和特定文化特性格式資訊的執行,可用來仲裁格式化程式。
IFormatProvider介面具有單一成員, GetFormat 其負責傳回提供格式資訊的物件。 .NET 有三個 IFormatProvider 可提供文化特性特定格式的執行:
CultureInfo. 它的方法會傳回 GetFormat 用來格式化數值的文化特性特定 NumberFormatInfo 物件,以及 DateTimeFormatInfo 用於格式化日期和時間值的文化特性特定物件。
DateTimeFormatInfo,用於日期和時間值的特定文化特性格式。 它的方法會傳回 GetFormat 本身。
NumberFormatInfo,用於數值的特定文化特性格式。 其 GetFormat 屬性會傳回本身。
自訂格式化作業
您也可以呼叫 Format 具有型別參數之方法的任何多載, provider
IFormatProvider 以執行自訂格式化作業。 例如,您可以將整數格式化為識別碼或電話號碼。 若要執行自訂格式設定,您 provider
的引數必須同時執行 IFormatProvider 和 ICustomFormatter 介面。 當 Format 方法傳遞 ICustomFormatter 實作為 provider
引數時, Format 方法會呼叫其實作為, IFormatProvider.GetFormat 並要求型別為的物件 ICustomFormatter 。 然後,它會呼叫傳回 ICustomFormatter 物件的 Format 方法,以將傳遞給它的複合字串中的每個格式專案格式化。
如需有關提供自訂格式設定解決方案的詳細資訊,請參閱 如何:定義和使用自訂數值格式提供者 和 ICustomFormatter 。 如需將整數轉換成格式化自訂數位的範例,請參閱 範例:自訂格式作業。 如需將不帶正負號的位元組轉換成羅馬數字的範例,請參閱 範例:攔截提供者和羅馬數字格式器。
範例:自訂格式化操作
這個範例會定義格式提供者,將整數值格式化為 x-xxxxx-xx 格式的客戶帳戶編號。
using namespace System;
ref class CustomerFormatter : IFormatProvider, ICustomFormatter
{
public:
virtual Object^ GetFormat(Type^ formatType)
{
if (formatType == ICustomFormatter::typeid)
return this;
else
return nullptr;
}
virtual String^ Format(String^ format,
Object^ arg,
IFormatProvider^ formatProvider)
{
if (! this->Equals(formatProvider))
{
return nullptr;
}
else
{
if (String::IsNullOrEmpty(format))
format = "G";
String^ customerString = arg->ToString();
if (customerString->Length < 8)
customerString = customerString->PadLeft(8, '0');
format = format->ToUpper();
if (format == L"G")
return customerString->Substring(0, 1) + "-" +
customerString->Substring(1, 5) + "-" +
customerString->Substring(6);
else if (format == L"S")
return customerString->Substring(0, 1) + "/" +
customerString->Substring(1, 5) + "/" +
customerString->Substring(6);
else if (format == L"P")
return customerString->Substring(0, 1) + "." +
customerString->Substring(1, 5) + "." +
customerString->Substring(6);
else
throw gcnew FormatException(
String::Format("The '{0}' format specifier is not supported.", format));
}
}
};
void main()
{
int acctNumber = 79203159;
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0}", acctNumber));
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:G}", acctNumber));
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:S}", acctNumber));
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:P}", acctNumber));
try {
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:X}", acctNumber));
}
catch (FormatException^ e) {
Console::WriteLine(e->Message);
}
}
// The example displays the following output:
// 7-92031-59
// 7-92031-59
// 7/92031/59
// 7.92031.59
// The 'X' format specifier is not supported.
using System;
public class TestFormatter
{
public static void Main()
{
int acctNumber = 79203159;
Console.WriteLine(String.Format(new CustomerFormatter(), "{0}", acctNumber));
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:G}", acctNumber));
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:S}", acctNumber));
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:P}", acctNumber));
try {
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:X}", acctNumber));
}
catch (FormatException e) {
Console.WriteLine(e.Message);
}
}
}
public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format,
object arg,
IFormatProvider formatProvider)
{
if (! this.Equals(formatProvider))
{
return null;
}
else
{
if (String.IsNullOrEmpty(format))
format = "G";
string customerString = arg.ToString();
if (customerString.Length < 8)
customerString = customerString.PadLeft(8, '0');
format = format.ToUpper();
switch (format)
{
case "G":
return customerString.Substring(0, 1) + "-" +
customerString.Substring(1, 5) + "-" +
customerString.Substring(6);
case "S":
return customerString.Substring(0, 1) + "/" +
customerString.Substring(1, 5) + "/" +
customerString.Substring(6);
case "P":
return customerString.Substring(0, 1) + "." +
customerString.Substring(1, 5) + "." +
customerString.Substring(6);
default:
throw new FormatException(
String.Format("The '{0}' format specifier is not supported.", format));
}
}
}
}
// The example displays the following output:
// 7-92031-59
// 7-92031-59
// 7/92031/59
// 7.92031.59
// The 'X' format specifier is not supported.
Module TestFormatter
Public Sub Main()
Dim acctNumber As Integer = 79203159
Console.WriteLine(String.Format(New CustomerFormatter, "{0}", acctNumber))
Console.WriteLine(String.Format(New CustomerFormatter, "{0:G}", acctNumber))
Console.WriteLine(String.Format(New CustomerFormatter, "{0:S}", acctNumber))
Console.WriteLine(String.Format(New CustomerFormatter, "{0:P}", acctNumber))
Try
Console.WriteLine(String.Format(New CustomerFormatter, "{0:X}", acctNumber))
Catch e As FormatException
Console.WriteLine(e.Message)
End Try
End Sub
End Module
Public Class CustomerFormatter : Implements IFormatProvider, ICustomFormatter
Public Function GetFormat(type As Type) As Object _
Implements IFormatProvider.GetFormat
If type Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
Public Function Format(fmt As String, _
arg As Object, _
formatProvider As IFormatProvider) As String _
Implements ICustomFormatter.Format
If Not Me.Equals(formatProvider) Then
Return Nothing
Else
If String.IsNullOrEmpty(fmt) Then fmt = "G"
Dim customerString As String = arg.ToString()
if customerString.Length < 8 Then _
customerString = customerString.PadLeft(8, "0"c)
Select Case fmt
Case "G"
Return customerString.Substring(0, 1) & "-" & _
customerString.Substring(1, 5) & "-" & _
customerString.Substring(6)
Case "S"
Return customerString.Substring(0, 1) & "/" & _
customerString.Substring(1, 5) & "/" & _
customerString.Substring(6)
Case "P"
Return customerString.Substring(0, 1) & "." & _
customerString.Substring(1, 5) & "." & _
customerString.Substring(6)
Case Else
Throw New FormatException( _
String.Format("The '{0}' format specifier is not supported.", fmt))
End Select
End If
End Function
End Class
' The example displays the following output:
' 7-92031-59
' 7-92031-59
' 7/92031/59
' 7.92031.59
' The 'X' format specifier is not supported.
範例:攔截器提供者和羅馬數字格式器
這個範例會定義自訂格式提供者,此提供者會 ICustomFormatter IFormatProvider 執行和介面來執行兩項作業:
它會顯示傳遞至其執行的參數 ICustomFormatter.Format 。 如此一來,我們就可以查看 Format(IFormatProvider, String, Object[]) 方法要針對每個嘗試格式化的物件,將哪些參數傳遞給自訂格式設定。 當您要對應用程式進行偵錯工具時,這會很有用。
如果要格式化的物件是要使用 "R" 標準格式字串格式化的不帶正負號的位元組值,自訂格式器會將數值格式化為羅馬數字。
using namespace System;
using namespace System::Globalization;
ref class InterceptProvider : IFormatProvider, ICustomFormatter
{
public:
virtual Object^ GetFormat(Type^ formatType)
{
if (formatType == ICustomFormatter::typeid)
return this;
else
return nullptr;
}
virtual String^ Format(String^ format, Object^ obj, IFormatProvider^ provider)
{
// Display information about method call.
String^ formatString = format != nullptr ? format : "<null>";
Console::WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
provider, obj != nullptr ? obj : "<null>", formatString);
if (obj == nullptr) return String::Empty;
// If this is a byte and the "R" format string, format it with Roman numerals.
if (obj->GetType() == Byte::typeid && formatString->ToUpper()->Equals("R")) {
Byte value = (Byte) obj;
int remainder;
int result;
String^ returnString = String::Empty;
// Get the hundreds digit(s)
result = Math::DivRem(value, 100, remainder);
if (result > 0)
returnString = gcnew String('C', result);
value = (Byte) remainder;
// Get the 50s digit
result = Math::DivRem(value, 50, remainder);
if (result == 1)
returnString += "L";
value = (Byte) remainder;
// Get the tens digit.
result = Math::DivRem(value, 10, remainder);
if (result > 0)
returnString += gcnew String('X', result);
value = (Byte) remainder;
// Get the fives digit.
result = Math::DivRem(value, 5, remainder);
if (result > 0)
returnString += "V";
value = (Byte) remainder;
// Add the ones digit.
if (remainder > 0)
returnString += gcnew String('I', remainder);
// Check whether we have too many X characters.
int pos = returnString->IndexOf("XXXX");
if (pos >= 0) {
int xPos = returnString->IndexOf("L");
if ((xPos >= 0) & (xPos == pos - 1))
returnString = returnString->Replace("LXXXX", "XC");
else
returnString = returnString->Replace("XXXX", "XL");
}
// Check whether we have too many I characters
pos = returnString->IndexOf("IIII");
if (pos >= 0)
if (returnString->IndexOf("V") >= 0)
returnString = returnString->Replace("VIIII", "IX");
else
returnString = returnString->Replace("IIII", "IV");
return returnString;
}
// Use default for all other formatting.
if (obj->GetType() == IFormattable::typeid)
return ((IFormattable^) obj)->ToString(format, CultureInfo::CurrentCulture);
else
return obj->ToString();
}
};
void main()
{
int n = 10;
double value = 16.935;
DateTime day = DateTime::Now;
InterceptProvider^ provider = gcnew InterceptProvider();
Console::WriteLine(String::Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day));
Console::WriteLine(String::Format(provider, "{0}: {1:F}\n", "Today: ",
(DayOfWeek) DateTime::Now.DayOfWeek));
Console::WriteLine(String::Format(provider, "{0:X}, {1}, {2}\n",
(Byte) 2, (Byte) 12, (Byte) 199));
Console::WriteLine(String::Format(provider, "{0:R}, {1:R}, {2:R}\n",
(Byte) 2, (Byte) 12, (Byte) 199));
}
// The example displays the following output:
// Provider: InterceptProvider, Object: 10, Format String: N0
// Provider: InterceptProvider, Object: 16.935, Format String: C2
// Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
// 10: $16.94 on 1/31/2013
//
// Provider: InterceptProvider, Object: Today: , Format String: <null>
// Provider: InterceptProvider, Object: Thursday, Format String: F
// Today: : Thursday
//
// Provider: InterceptProvider, Object: 2, Format String: X
// Provider: InterceptProvider, Object: 12, Format String: <null>
// Provider: InterceptProvider, Object: 199, Format String: <null>
// 2, 12, 199
//
// Provider: InterceptProvider, Object: 2, Format String: R
// Provider: InterceptProvider, Object: 12, Format String: R
// Provider: InterceptProvider, Object: 199, Format String: R
// II, XII, CXCIX
using System;
using System.Globalization;
public class InterceptProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(String format, Object obj, IFormatProvider provider)
{
// Display information about method call.
string formatString = format ?? "<null>";
Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
provider.GetType().Name, obj ?? "<null>", formatString);
if (obj == null) return String.Empty;
// If this is a byte and the "R" format string, format it with Roman numerals.
if (obj is Byte && formatString.ToUpper().Equals("R")) {
Byte value = (Byte) obj;
int remainder;
int result;
String returnString = String.Empty;
// Get the hundreds digit(s)
result = Math.DivRem(value, 100, out remainder);
if (result > 0)
returnString = new String('C', result);
value = (Byte) remainder;
// Get the 50s digit
result = Math.DivRem(value, 50, out remainder);
if (result == 1)
returnString += "L";
value = (Byte) remainder;
// Get the tens digit.
result = Math.DivRem(value, 10, out remainder);
if (result > 0)
returnString += new String('X', result);
value = (Byte) remainder;
// Get the fives digit.
result = Math.DivRem(value, 5, out remainder);
if (result > 0)
returnString += "V";
value = (Byte) remainder;
// Add the ones digit.
if (remainder > 0)
returnString += new String('I', remainder);
// Check whether we have too many X characters.
int pos = returnString.IndexOf("XXXX");
if (pos >= 0) {
int xPos = returnString.IndexOf("L");
if (xPos >= 0 & xPos == pos - 1)
returnString = returnString.Replace("LXXXX", "XC");
else
returnString = returnString.Replace("XXXX", "XL");
}
// Check whether we have too many I characters
pos = returnString.IndexOf("IIII");
if (pos >= 0)
if (returnString.IndexOf("V") >= 0)
returnString = returnString.Replace("VIIII", "IX");
else
returnString = returnString.Replace("IIII", "IV");
return returnString;
}
// Use default for all other formatting.
if (obj is IFormattable)
return ((IFormattable) obj).ToString(format, CultureInfo.CurrentCulture);
else
return obj.ToString();
}
}
public class Example
{
public static void Main()
{
int n = 10;
double value = 16.935;
DateTime day = DateTime.Now;
InterceptProvider provider = new InterceptProvider();
Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day));
Console.WriteLine(String.Format(provider, "{0}: {1:F}\n", "Today: ",
(DayOfWeek) DateTime.Now.DayOfWeek));
Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n",
(Byte) 2, (Byte) 12, (Byte) 199));
Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}\n",
(Byte) 2, (Byte) 12, (Byte) 199));
}
}
// The example displays the following output:
// Provider: InterceptProvider, Object: 10, Format String: N0
// Provider: InterceptProvider, Object: 16.935, Format String: C2
// Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
// 10: $16.94 on 1/31/2013
//
// Provider: InterceptProvider, Object: Today: , Format String: <null>
// Provider: InterceptProvider, Object: Thursday, Format String: F
// Today: : Thursday
//
// Provider: InterceptProvider, Object: 2, Format String: X
// Provider: InterceptProvider, Object: 12, Format String: <null>
// Provider: InterceptProvider, Object: 199, Format String: <null>
// 2, 12, 199
//
// Provider: InterceptProvider, Object: 2, Format String: R
// Provider: InterceptProvider, Object: 12, Format String: R
// Provider: InterceptProvider, Object: 199, Format String: R
// II, XII, CXCIX
Imports System.Globalization
Public Class InterceptProvider : Implements IFormatProvider, ICustomFormatter
Public Function GetFormat(formatType As Type) As Object _
Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
Public Function Format(fmt As String, obj As Object, provider As IFormatProvider) As String _
Implements ICustomFormatter.Format
Dim formatString As String = If(fmt IsNot Nothing, fmt, "<null>")
Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
provider, If(obj IsNot Nothing, obj, "<null>"), formatString)
If obj Is Nothing Then Return String.Empty
' If this is a byte and the "R" format string, format it with Roman numerals.
If TypeOf(obj) Is Byte AndAlso formatString.ToUpper.Equals("R") Then
Dim value As Byte = CByte(obj)
Dim remainder As Integer
Dim result As Integer
Dim returnString As String = String.Empty
' Get the hundreds digit(s)
result = Math.DivRem(value, 100, remainder)
If result > 0 Then returnString = New String("C"c, result)
value = CByte(remainder)
' Get the 50s digit
result = Math.DivRem(value, 50, remainder)
If result = 1 Then returnString += "L"
value = CByte(remainder)
' Get the tens digit.
result = Math.DivRem(value, 10, remainder)
If result > 0 Then returnString += New String("X"c, result)
value = CByte(remainder)
' Get the fives digit.
result = Math.DivRem(value, 5, remainder)
If result > 0 Then returnString += "V"
value = CByte(remainder)
' Add the ones digit.
If remainder > 0 Then returnString += New String("I"c, remainder)
' Check whether we have too many X characters.
Dim pos As Integer = returnString.IndexOf("XXXX")
If pos >= 0 Then
Dim xPos As Integer = returnString.IndexOf("L")
If xPos >= 0 And xPos = pos - 1 Then
returnString = returnString.Replace("LXXXX", "XC")
Else
returnString = returnString.Replace("XXXX", "XL")
End If
End If
' Check whether we have too many I characters
pos = returnString.IndexOf("IIII")
If pos >= 0 Then
If returnString.IndexOf("V") >= 0 Then
returnString = returnString.Replace("VIIII", "IX")
Else
returnString = returnString.Replace("IIII", "IV")
End If
End If
Return returnString
End If
' Use default for all other formatting.
If obj Is GetType(IFormattable)
Return CType(obj, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
Else
Return obj.ToString()
End If
End Function
End Class
Module Example
Public Sub Main()
Dim n As Integer = 10
Dim value As Double = 16.935
Dim day As DateTime = Date.Now
Dim provider As New InterceptProvider()
Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}", n, value, day))
Console.WriteLine()
Console.WriteLine(String.Format(provider, "{0}: {1:F}", "Today",
CType(Date.Now.DayOfWeek, DayOfWeek)))
Console.WriteLine()
Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n",
CByte(2), CByte(12), CByte(199)))
Console.WriteLine()
Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}",
CByte(2), CByte(12), CByte(199)))
End Sub
End Module
' The example displays the following output:
' Provider: InterceptProvider, Object: 10, Format String: N0
' Provider: InterceptProvider, Object: 16.935, Format String: C2
' Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
' 10: $16.94 on 1/31/2013
'
' Provider: InterceptProvider, Object: Today: , Format String: <null>
' Provider: InterceptProvider, Object: Thursday, Format String: F
' Today: : Thursday
'
' Provider: InterceptProvider, Object: 2, Format String: X
' Provider: InterceptProvider, Object: 12, Format String: <null>
' Provider: InterceptProvider, Object: 199, Format String: <null>
' 2, 12, 199
'
' Provider: InterceptProvider, Object: 2, Format String: R
' Provider: InterceptProvider, Object: 12, Format String: R
' Provider: InterceptProvider, Object: 199, Format String: R
' II, XII, CXCIX
字串。格式 Q & A
為什麼您會在呼叫方法時建議字串插補 String.Format
?
字串插補為:
更有彈性。 您可以在任何字串中使用它,而不需要呼叫支援複合格式的方法。 否則,您必須呼叫 Format 方法或另一個支援複合格式的方法,例如 Console.WriteLine 或 StringBuilder.AppendFormat 。
更容易閱讀。 因為插入字串中的運算式會出現在插入運算式中,而不是在引數清單中,所以插入的字串會比較容易編碼和讀取。 因為插入字串的可讀性較高,所以無法只取代複合格式方法的呼叫,但是也可以在字串串連作業中使用,以產生更簡潔、更清楚的程式碼。
下列兩個程式碼範例的比較說明如何優勢字串串連和複合格式方法的呼叫中的字串插值。 在下列範例中,使用多個字串串連作業會產生詳細資訊和難以閱讀的程式碼。
string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
string output = names[0] + ", " + names[1] + ", " + names[2] + ", " +
names[3] + ", " + names[4] + ", " + names[5] + ", " +
names[6];
output += "\n";
var date = DateTime.Now;
output += String.Format("It is {0:t} on {0:d}. The day of the week is {1}.",
date, date.DayOfWeek);
Console.WriteLine(output);
// The example displays the following output:
// Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
// It is 10:29 AM on 1/8/2018. The day of the week is Monday.
Module Example
Public Sub Main()
Dim names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" }
Dim output = names(0) + ", " + names(1) + ", " + names(2) + ", " +
names(3) + ", " + names(4) + ", " + names(5) + ", " +
names(6)
output += vbCrLf
Dim dat = DateTime.Now
output += String.Format("It is {0:t} on {0:d}. The day of the week is {1}.",
dat, dat.DayOfWeek)
Console.WriteLine(output)
End Sub
End Module
' The example displays the following output:
' Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
' It is 10:29 AM on 1/8/2018. The day of the week is Monday.
相較之下,在下列範例中使用插入字串,會產生比字串串連語句更清楚、更簡潔的程式碼,以及對 Format 前一個範例中的方法的呼叫。
string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
string output = $"{names[0]}, {names[1]}, {names[2]}, {names[3]}, {names[4]}, " +
$"{names[5]}, {names[6]}";
var date = DateTime.Now;
output += $"\nIt is {date:t} on {date:d}. The day of the week is {date.DayOfWeek}.";
Console.WriteLine(output);
// The example displays the following output:
// Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
// It is 10:29 AM on 1/8/2018. The day of the week is Monday.
Module Example
Public Sub Main()
Dim names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" }
Dim output = $"{names(0)}, {names(1)}, {names(2)}, {names(3)}, {names(4)}, " +
$"{names(5)}, {names(6)}"
Dim dat = DateTime.Now
output += $"{vbCrLf}It is {dat:t} on {dat:d}. The day of the week is {dat.DayOfWeek}."
Console.WriteLine(output)
End Sub
End Module
' The example displays the following output:
' Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
' It is 10:29 AM on 1/8/2018. The day of the week is Monday.
哪裡可以找到可與格式專案搭配使用的預先定義格式字串清單?
如需日期和時間值,請參閱 標準日期和時間格式字串 ,以及 自訂日期和時間格式字串。
如需列舉值,請參閱 列舉格式字串。
如需 TimeSpan 值,請參閱 標準 Timespan 格式字串 和 自訂 timespan 格式字串。
如需 Guid 值,請參閱參考頁面的備註一節 Guid.ToString(String) 。
如何? 控制取代格式專案之結果字串的對齊方式?
格式專案的一般語法如下:
{index[,alignment][: formatString]}
其中, 對齊 是定義欄位寬度的帶正負號整數。 如果這個值是負數,則欄位中的文字會靠左對齊。 如果是正數,則文字會靠右對齊。
如何? 控制小數分隔符號之後的位數?
所有 標準數值格式字串 ("D" 除外) (只用于整數) 、"G"、"R" 和 "X" 的精確度規範,允許定義結果字串中的小數位數。 下列範例會使用標準數值格式字串來控制結果字串中的小數位數。
object[] values = { 1603, 1794.68235, 15436.14 };
string result;
foreach (var value in values) {
result = String.Format("{0,12:C2} {0,12:E3} {0,12:F4} {0,12:N3} {1,12:P2}\n",
Convert.ToDouble(value), Convert.ToDouble(value) / 10000);
Console.WriteLine(result);
}
// The example displays output like the following:
// $1,603.00 1.603E+003 1603.0000 1,603.000 16.03 %
//
// $1,794.68 1.795E+003 1794.6824 1,794.682 17.95 %
//
// $15,436.14 1.544E+004 15436.1400 15,436.140 154.36 %
Module Example
Public Sub Main()
Dim values() As Object = { 1603, 1794.68235, 15436.14 }
Dim result As String
For Each value In values
result = String.Format("{0,12:C2} {0,12:E3} {0,12:F4} {0,12:N3} {1,12:P2}",
value, CDbl(value) / 10000)
Console.WriteLine(result)
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' $1,603.00 1.603E+003 1603.0000 1,603.000 16.03 %
'
' $1,794.68 1.795E+003 1794.6824 1,794.682 17.95 %
'
' $15,436.14 1.544E+004 15436.1400 15,436.140 154.36 %
如果您要使用 自訂數值格式字串,請使用 "0" 格式規範來控制結果字串中的小數位數,如下列範例所示。
decimal value = 16309.5436m;
string result = String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}",
value);
Console.WriteLine(result);
// The example displays the following output:
// 16309.54360 16,309.54 16309.544
Module Example
Public Sub Main()
Dim value As Decimal = 16309.5436d
Dim result As String = String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}",
value)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 16309.54360 16,309.54 16309.544
如何? 控制整數的位數?
根據預設,格式化作業只會顯示非零的整數數位。 如果您要將整數格式化,可以使用具有 "D" 和 "X" 標準格式字串的精確度規範來控制位數。
int value = 1326;
string result = String.Format("{0,10:D6} {0,10:X8}", value);
Console.WriteLine(result);
// The example displays the following output:
// 001326 0000052E
Module Example
Public Sub Main()
Dim value As Integer = 1326
Dim result As String = String.Format("{0,10:D6} {0,10:X8}", value)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 001326 0000052E
您可以使用「0」 自訂數值格式規範來填補具有前置零的整數或浮點數,以產生具有指定整數位數的結果字串,如下列範例所示。
int value = 16342;
string result = String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}",
value);
Console.WriteLine(result);
// The example displays the following output:
// 00016342 00016342.000 0,000,016,342.0
Module Example
Public Sub Main()
Dim value As Integer = 16342
Dim result As String = String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}",
value)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 00016342 00016342.000 0,000,016,342.0
我可以在格式清單中包含多少個專案?
沒有實際限制。 方法的第二個參數 Format(IFormatProvider, String, Object[]) 會以屬性標記 ParamArrayAttribute ,可讓您包含分隔清單或物件陣列做為您的格式清單。
如何? 在結果字串中包含常值大括弧 ( "{" 和 "}" ) ?
例如,您如何防止下列方法呼叫擲回 FormatException 例外狀況?
result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
nOpen, nClose);
result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
nOpen, nClose)
單一開頭或右大括弧一律會轉譯為格式專案的開頭或結尾。 若要以逐字的方式進行解讀,必須將其設為轉義。 您可以藉由將另一個大括弧 ( "{{" 和 "}}" 取代 "{" 和 "}" ) 來 escape 括弧,如下列方法呼叫所示:
string result;
int nOpen = 1;
int nClose = 2;
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
nOpen, nClose);
Console.WriteLine(result);
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
nOpen, nClose)
但是,即使是可輕易地誤解的,也可以輕易地誤解括弧。 建議您在格式清單中包含大括弧,並使用格式專案將它們插入結果字串,如下列範例所示。
string result;
int nOpen = 1;
int nClose = 2;
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
nOpen, "{", nClose, "}");
Console.WriteLine(result);
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
nOpen, "{", nClose, "}")
為什麼我呼叫字串. Format 方法會擲回 >formatexception?
例外狀況最常見的原因是格式專案的索引不會對應至格式清單中的物件。 這通常表示您已 misnumbered 格式專案的索引,或您忘記在格式清單中包含物件。 嘗試包含非空白的左或右大括弧字元也會擲回 FormatException 。 有時候,例外狀況是打字錯誤的結果;例如,常見的錯誤是將 "[" (左括弧) ,而不是 "{" (左大括弧) 。
如果 (IFormatProvider,System.string,System.object [] ) 方法的格式支援參數陣列,當我使用陣列時,為什麼我的程式碼會擲回例外狀況?
例如,下列程式碼會擲回 FormatException 例外狀況:
Random rnd = new Random();
int[] numbers = new int[4];
int total = 0;
for (int ctr = 0; ctr <= 2; ctr++) {
int number = rnd.Next(1001);
numbers[ctr] = number;
total += number;
}
numbers[3] = total;
Console.WriteLine("{0} + {1} + {2} = {3}", numbers);
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim rnd As New Random()
Dim numbers(3) As Integer
Dim total As Integer = 0
For ctr = 0 To 2
Dim number As Integer = rnd.Next(1001)
numbers(ctr) = number
total += number
Next
numbers(3) = total
Console.WriteLine("{0} + {1} + {2} = {3}", numbers)
End Sub
End Module
這是編譯器多載解析的問題。 因為編譯器無法將整數陣列轉換成物件陣列,所以會將整數陣列視為單一引數,因此它會呼叫 Format(String, Object) 方法。 擲回例外狀況的原因是有四個格式專案,但只有格式清單中的單一專案。
由於 Visual Basic 或 c # 都不能將整數陣列轉換成物件陣列,因此您必須先執行轉換,再呼叫 Format(String, Object[]) 方法。 下列範例提供一個實作為。
Random rnd = new Random();
int[] numbers = new int[4];
int total = 0;
for (int ctr = 0; ctr <= 2; ctr++) {
int number = rnd.Next(1001);
numbers[ctr] = number;
total += number;
}
numbers[3] = total;
object[] values = new object[numbers.Length];
numbers.CopyTo(values, 0);
Console.WriteLine("{0} + {1} + {2} = {3}", values);
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim rnd As New Random()
Dim numbers(3) As Integer
Dim total As Integer = 0
For ctr = 0 To 2
Dim number As Integer = rnd.Next(1001)
numbers(ctr) = number
total += number
Next
numbers(3) = total
Dim values(numbers.Length - 1) As Object
numbers.CopyTo(values, 0)
Console.WriteLine("{0} + {1} + {2} = {3}", values)
End Sub
End Module
Format(String, Object)
以指定物件的字串表示,取代字串中的一或多個格式項目。
public:
static System::String ^ Format(System::String ^ format, System::Object ^ arg0);
public static string Format (string format, object arg0);
public static string Format (string format, object? arg0);
static member Format : string * obj -> string
Public Shared Function Format (format As String, arg0 As Object) As String
參數
- arg0
- Object
要格式化的物件。
傳回
format
的複本,其中的所有格式項目已由 arg0
的字串表示取代。
例外狀況
format
為 null
。
備註
重要
請不要呼叫 String.Format 方法或使用 複合格式字串,您可以使用「內插字串」(如果您的語言支援它們的話)。 內插字串是包含「插入運算式」的字串。 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。 如需詳細資訊,請參閱內插字串 (C# 參考) 和內插字串 (Visual Basic 參考)。
這個方法會使用 複合格式功能 將運算式的值轉換成其字串表示,並在字串中內嵌該標記法。
不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。 相反地,您可以使用包含一或多個格式項目的複合格式字串來呼叫該方法。 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。
如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門和 要呼叫哪個方法?。
範例:格式化單一引數
下列範例會使用 Format(String, Object) 方法,將個人的年齡內嵌在字串的中間。
using namespace System;
void main()
{
DateTime birthdate = DateTime(1993, 7, 28);
array<DateTime>^ dates = gcnew array<DateTime> { DateTime(1993, 8, 16),
DateTime(1994, 7, 28),
DateTime(2000, 10, 16),
DateTime(2003, 7, 27),
DateTime(2007, 5, 27) };
for each (DateTime dateValue in dates)
{
TimeSpan interval = dateValue - birthdate;
// Get the approximate number of years, without accounting for leap years.
int years = ((int)interval.TotalDays) / 365;
// See if adding the number of years exceeds dateValue.
String^ output;
if (birthdate.AddYears(years) <= dateValue) {
output = String::Format("You are now {0} years old.", years);
Console::WriteLine(output);
}
else {
output = String::Format("You are now {0} years old.", years - 1);
Console::WriteLine(output);
}
}
}
// The example displays the following output:
// You are now 0 years old.
// You are now 1 years old.
// You are now 7 years old.
// You are now 9 years old.
// You are now 13 years old.
DateTime birthdate = new DateTime(1993, 7, 28);
DateTime[] dates = { new DateTime(1993, 8, 16),
new DateTime(1994, 7, 28),
new DateTime(2000, 10, 16),
new DateTime(2003, 7, 27),
new DateTime(2007, 5, 27) };
foreach (DateTime dateValue in dates)
{
TimeSpan interval = dateValue - birthdate;
// Get the approximate number of years, without accounting for leap years.
int years = ((int) interval.TotalDays) / 365;
// See if adding the number of years exceeds dateValue.
string output;
if (birthdate.AddYears(years) <= dateValue) {
output = String.Format("You are now {0} years old.", years);
Console.WriteLine(output);
}
else {
output = String.Format("You are now {0} years old.", years - 1);
Console.WriteLine(output);
}
}
// The example displays the following output:
// You are now 0 years old.
// You are now 1 years old.
// You are now 7 years old.
// You are now 9 years old.
// You are now 13 years old.
Module Example
Public Sub Main()
Dim birthdate As Date = #7/28/1993#
Dim dates() As Date = { #9/16/1993#, #7/28/1994#, #10/16/2000#, _
#7/27/2003#, #5/27/2007# }
For Each dateValue As Date In dates
Dim interval As TimeSpan = dateValue - birthdate
' Get the approximate number of years, without accounting for leap years.
Dim years As Integer = CInt(interval.TotalDays) \ 365
' See if adding the number of years exceeds dateValue.
Dim output As String
If birthdate.AddYears(years) <= dateValue Then
output = String.Format("You are now {0} years old.", years)
Console.WriteLine(output)
Else
output = String.Format("You are now {0} years old.", years - 1)
Console.WriteLine(output)
End If
Next
End Sub
End Module
' The example displays the following output:
' You are now 0 years old.
' You are now 1 years old.
' You are now 7 years old.
' You are now 9 years old.
' You are now 13 years old.
另請參閱
- 在 .NET 中將類型格式化
- 複合格式
- 標準日期和時間格式字串
- 自訂日期和時間格式字串
- 標準數值格式字串
- 自訂數值格式字串
- 標準 TimeSpan 格式字串
- 自訂 TimeSpan 格式字串
- 列舉格式字串
適用於
Format(String, Object[])
以指定陣列中對應物件的字串表示,取代指定之字串中的格式項目。
public:
static System::String ^ Format(System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (string format, params object[] args);
public static string Format (string format, params object?[] args);
static member Format : string * obj[] -> string
Public Shared Function Format (format As String, ParamArray args As Object()) As String
參數
- args
- Object[]
物件陣列,包含零或多個要格式化的物件。
傳回
format
的複本,其中的格式項目已由 args
中對應物件的字串表示取代。
例外狀況
format
或 args
為 null
。
備註
重要
請不要呼叫 String.Format 方法或使用 複合格式字串,您可以使用「內插字串」(如果您的語言支援它們的話)。 內插字串是包含「插入運算式」的字串。 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。 如需詳細資訊,請參閱內插字串 (C# 參考) 和內插字串 (Visual Basic 參考)。
這個方法會使用 複合格式化功能 ,將四個或更多運算式的值轉換成其字串表示,並在字串中內嵌這些表示。 因為 args
參數是以 System.ParamArrayAttribute 屬性標記,所以您可以將物件以個別引數或陣列的形式傳遞給方法 Object 。
不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。 相反地,您可以使用包含一或多個格式項目的複合格式字串來呼叫該方法。 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。
如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門和 要呼叫哪個方法?。
範例:格式化三個以上的引數
這個範例會建立一個字串,其中包含特定日期的高和低溫度資料。 複合格式字串在 c # 範例中有五個格式專案,而 Visual Basic 範例中有六個格式專案。 其中兩個格式專案會定義其對應值之字串表示的寬度,而第一個格式專案也包含標準日期和時間格式字串。
using namespace System;
void main()
{
DateTime date1 = DateTime(2009, 7, 1);
TimeSpan hiTime = TimeSpan(14, 17, 32);
Decimal hiTemp = (Decimal) 62.1;
TimeSpan loTime = TimeSpan(3, 16, 10);
Decimal loTemp = (Decimal)54.8;
String^ result1 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
date1, hiTime, hiTemp, loTime, loTemp);
Console::WriteLine(result1);
Console::WriteLine();
String^ result2 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
gcnew array<Object^> { date1, hiTime, hiTemp, loTime, loTemp });
Console::WriteLine(result2);
}
// The example displays the following output:
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
DateTime date1 = new DateTime(2009, 7, 1);
TimeSpan hiTime = new TimeSpan(14, 17, 32);
decimal hiTemp = 62.1m;
TimeSpan loTime = new TimeSpan(3, 16, 10);
decimal loTemp = 54.8m;
string result1 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
date1, hiTime, hiTemp, loTime, loTemp);
Console.WriteLine(result1);
Console.WriteLine();
string result2 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
new object[] { date1, hiTime, hiTemp, loTime, loTemp });
Console.WriteLine(result2);
// The example displays output like the following:
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
Module Example
Public Sub Main()
Dim date1 As Date = #7/1/2009#
Dim hiTime As New TimeSpan(14, 17, 32)
Dim hiTemp As Decimal = 62.1d
Dim loTime As New TimeSpan(3, 16, 10)
Dim loTemp As Decimal = 54.8d
Dim result1 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
date1, hiTime, hiTemp, loTime, loTemp, vbCrLf)
Console.WriteLine(result1)
Console.WriteLine()
Dim result2 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
New Object() { date1, hiTime, hiTemp, loTime, loTemp, vbCrLf })
Console.WriteLine(result2)
End Sub
End Module
' The example displays the following output:
' Temperature on 7/1/2009:
' 14:17:32: 62.1 degrees (hi)
' 03:16:10: 54.8 degrees (lo)
'
' Temperature on 7/1/2009:
' 14:17:32: 62.1 degrees (hi)
' 03:16:10: 54.8 degrees (lo)
您也可以傳遞要格式化為陣列的物件,而不是引數清單。
using namespace System;
ref class CityInfo
{
public:
CityInfo(String^ name, int population, Decimal area, int year)
{
this->Name = name;
this->Population = population;
this->Area = area;
this->Year = year;
}
String^ Name;
int Population;
Decimal Area;
int Year;
};
ref class Example
{
public:
static void ShowPopulationData(CityInfo^ city)
{
array<Object^>^ args = gcnew array<Object^> { city->Name, city->Year, city->Population, city->Area };
String^ result = String::Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet",
args);
Console::WriteLine(result);
}
};
void main()
{
CityInfo^ nyc2010 = gcnew CityInfo("New York", 8175133, (Decimal) 302.64, 2010);
Example::ShowPopulationData(nyc2010);
CityInfo^ sea2010 = gcnew CityInfo("Seattle", 608660, (Decimal) 83.94, 2010);
Example::ShowPopulationData(sea2010);
}
// The example displays the following output:
// New York in 2010: Population 8,175,133, Area 302.6 sq. feet
// Seattle in 2010: Population 608,660, Area 83.9 sq. feet
using System;
public class CityInfo
{
public CityInfo(String name, int population, Decimal area, int year)
{
this.Name = name;
this.Population = population;
this.Area = area;
this.Year = year;
}
public readonly String Name;
public readonly int Population;
public readonly Decimal Area;
public readonly int Year;
}
public class Example
{
public static void Main()
{
CityInfo nyc2010 = new CityInfo("New York", 8175133, 302.64m, 2010);
ShowPopulationData(nyc2010);
CityInfo sea2010 = new CityInfo("Seattle", 608660, 83.94m, 2010);
ShowPopulationData(sea2010);
}
private static void ShowPopulationData(CityInfo city)
{
object[] args = { city.Name, city.Year, city.Population, city.Area };
String result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet",
args);
Console.WriteLine(result);
}
}
// The example displays the following output:
// New York in 2010: Population 8,175,133, Area 302.6 sq. feet
// Seattle in 2010: Population 608,660, Area 83.9 sq. feet
Public Class CityInfo
Public Sub New(name As String, population As Integer, area As Decimal, year As Integer)
Me.Name = name
Me.Population = population
Me.Area = area
Me.Year = year
End Sub
Public ReadOnly Name As String
Public ReadOnly Population As Integer
Public ReadOnly Area As Decimal
Public ReadOnly Year As Integer
End Class
Module Example
Public Sub Main()
Dim nyc2010 As New CityInfo("New York", 8175133, 302.64d, 2010)
ShowPopulationData(nyc2010)
Dim sea2010 As New CityInfo("Seattle", 608660, 83.94d, 2010)
ShowPopulationData(sea2010)
End Sub
Private Sub ShowPopulationData(city As CityInfo)
Dim args() As Object = { city.Name, city.Year, city.Population, city.Area }
Dim result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", args)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' New York in 2010: Population 8,175,133, Area 302.6 sq. feet
' Seattle in 2010: Population 608,660, Area 83.9 sq. feet
另請參閱
- 在 .NET 中將類型格式化
- 複合格式
- 標準日期和時間格式字串
- 自訂日期和時間格式字串
- 標準數值格式字串
- 自訂數值格式字串
- 標準 TimeSpan 格式字串
- 自訂 TimeSpan 格式字串
- 列舉格式字串
適用於
Format(IFormatProvider, String, Object)
以對應物件的字串表示,取代指定之字串中的一或多個格式項目。 參數提供特定文化特性格式資訊。
public:
static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0);
public static string Format (IFormatProvider provider, string format, object arg0);
public static string Format (IFormatProvider? provider, string format, object? arg0);
static member Format : IFormatProvider * string * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object) As String
參數
- provider
- IFormatProvider
物件,提供特定文化特性格式資訊。
- arg0
- Object
要格式化的物件。
傳回
format
的複本,其中的一或多個格式項目已由 arg0
的字串表示取代。
例外狀況
format
為 null
。
備註
重要
請不要呼叫 String.Format 方法或使用 複合格式字串,您可以使用「內插字串」(如果您的語言支援它們的話)。 內插字串是包含「插入運算式」的字串。 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。 如需詳細資訊,請參閱內插字串 (C# 參考) 和內插字串 (Visual Basic 參考)。
這個方法會使用 複合格式功能 將運算式的值轉換成其字串表示,並在字串中內嵌該標記法。 在執行轉換時,方法會使用區分文化特性的格式或自訂格式器。 方法會藉 arg0
由呼叫其 Tostring (IFormatProvider) 方法,或如果物件的對應格式專案包含格式字串,藉由呼叫其 Tostring (string,IFormatProvider) 方法,來轉換為其字串表示。 如果這些方法不存在,則會呼叫物件的無參數 ToString 方法。
不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。 相反地,您可以使用提供區分文化特性或自訂格式的物件和包含一或多個格式項目的複合格式字串來呼叫該方法。 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。
如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門和 要呼叫哪個方法?。
適用於
Format(IFormatProvider, String, Object[])
以指定陣列中對應物件的字串表示,取代字串中的格式項目。 參數提供特定文化特性格式資訊。
public:
static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (IFormatProvider provider, string format, params object[] args);
public static string Format (IFormatProvider? provider, string format, params object?[] args);
static member Format : IFormatProvider * string * obj[] -> string
Public Shared Function Format (provider As IFormatProvider, format As String, ParamArray args As Object()) As String
參數
- provider
- IFormatProvider
物件,提供特定文化特性格式資訊。
- args
- Object[]
物件陣列,包含零或多個要格式化的物件。
傳回
format
的複本,其中的格式項目已由 args
中對應物件的字串表示取代。
例外狀況
format
或 args
為 null
。
備註
重要
請不要呼叫 String.Format 方法或使用 複合格式字串,您可以使用「內插字串」(如果您的語言支援它們的話)。 內插字串是包含「插入運算式」的字串。 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。 如需詳細資訊,請參閱內插字串 (C# 參考) 和內插字串 (Visual Basic 參考)。
這個方法會使用 複合格式化功能 ,將四個或更多的運算式轉換成其字串表示,並將這些標記法內嵌在字串中。 在執行轉換時,方法會使用區分文化特性的格式或自訂格式器。 方法會藉 Object 由呼叫其 Tostring (IFormatProvider) 方法,將每個引數轉換成其字串表示,或者,如果物件的對應格式專案包含格式字串,請呼叫其 Tostring (string,IFormatProvider) 方法。 如果這些方法不存在,則會呼叫物件的無參數 ToString 方法。
不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。 相反地,您可以使用提供區分文化特性或自訂格式的物件和包含一或多個格式項目的複合格式字串來呼叫該方法。 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。
如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門和 要呼叫哪個方法?。
範例:區分文化特性的格式
這個範例會使用 Format(IFormatProvider, String, Object[]) 方法來顯示某些日期和時間值的字串表示,以及使用數種不同文化特性的數值。
string[] cultureNames = { "en-US", "fr-FR", "de-DE", "es-ES" };
DateTime dateToDisplay = new DateTime(2009, 9, 1, 18, 32, 0);
double value = 9164.32;
Console.WriteLine("Culture Date Value\n");
foreach (string cultureName in cultureNames)
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
string output = String.Format(culture, "{0,-11} {1,-35:D} {2:N}",
culture.Name, dateToDisplay, value);
Console.WriteLine(output);
}
// The example displays the following output:
// Culture Date Value
//
// en-US Tuesday, September 01, 2009 9,164.32
// fr-FR mardi 1 septembre 2009 9 164,32
// de-DE Dienstag, 1. September 2009 9.164,32
// es-ES martes, 01 de septiembre de 2009 9.164,32
Imports System.Globalization
Module Example
Public Sub Main()
Dim cultureNames() As String = { "en-US", "fr-FR", "de-DE", "es-ES" }
Dim dateToDisplay As Date = #9/1/2009 6:32PM#
Dim value As Double = 9164.32
Console.WriteLine("Culture Date Value")
Console.WriteLine()
For Each cultureName As String In cultureNames
Dim culture As New CultureInfo(cultureName)
Dim output As String = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", _
culture.Name, dateToDisplay, value)
Console.WriteLine(output)
Next
End Sub
End Module
' The example displays the following output:
' Culture Date Value
'
' en-US Tuesday, September 01, 2009 9,164.32
' fr-FR mardi 1 septembre 2009 9 164,32
' de-DE Dienstag, 1. September 2009 9.164,32
' es-ES martes, 01 de septiembre de 2009 9.164,32
另請參閱
- DateTimeFormatInfo
- ICustomFormatter
- IFormatProvider
- NumberFormatInfo
- 在 .NET 中將類型格式化
- 複合格式
- 標準日期和時間格式字串
- 自訂日期和時間格式字串
- 標準數值格式字串
- 自訂數值格式字串
- 標準 TimeSpan 格式字串
- 自訂 TimeSpan 格式字串
- 列舉格式字串
適用於
Format(String, Object, Object)
以兩個指定物件的字串表示,取代字串中的格式項目。
public:
static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (string format, object arg0, object arg1);
public static string Format (string format, object? arg0, object? arg1);
static member Format : string * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object) As String
參數
- arg0
- Object
要格式化的第一個物件。
- arg1
- Object
要格式化的第二個物件。
傳回
format
的複本,其中的格式項目已由 arg0
和 arg1
的字串表示取代。
例外狀況
format
為 null
。
備註
重要
請不要呼叫 String.Format 方法或使用 複合格式字串,您可以使用「內插字串」(如果您的語言支援它們的話)。 內插字串是包含「插入運算式」的字串。 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。 如需詳細資訊,請參閱內插字串 (C# 參考) 和內插字串 (Visual Basic 參考)。
這個方法會使用 複合格式化功能 ,將兩個運算式的值轉換成其字串表示,並將這些標記法內嵌在字串中。
不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。 相反地,您可以使用包含一或多個格式項目的複合格式字串來呼叫該方法。 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。
如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門和 要呼叫哪個方法?。
範例:格式化兩個引數
這個範例會使用 Format(String, Object, Object) 方法來顯示儲存在泛型物件中的時間和溫度資料 Dictionary<TKey,TValue> 。 請注意,格式字串有三個格式專案,雖然只有兩個要格式化的物件。 這是因為清單中的第一個物件 (日期和時間值) 由兩個格式專案所使用:第一個格式專案會顯示時間,而第二個會顯示日期。
using namespace System;
using namespace System::Collections::Generic;
void main()
{
Dictionary<DateTime, Double>^ temperatureInfo = gcnew Dictionary<DateTime, Double>();
temperatureInfo->Add(DateTime(2010, 6, 1, 14, 0, 0), 87.46);
temperatureInfo->Add(DateTime(2010, 12, 1, 10, 0, 0), 36.81);
Console::WriteLine("Temperature Information:\n");
String^ output;
for each (KeyValuePair<DateTime, Double>^ item in temperatureInfo)
{
output = String::Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}�F",
item->Key, item->Value);
Console::WriteLine(output);
}
}
// The example displays the following output:
// Temperature Information:
//
// Temperature at 2:00 PM on 6/1/2010: 87.5�F
// Temperature at 10:00 AM on 12/1/2010: 36.8�F
Dictionary<DateTime, Double> temperatureInfo = new Dictionary<DateTime, Double>();
temperatureInfo.Add(new DateTime(2010, 6, 1, 14, 0, 0), 87.46);
temperatureInfo.Add(new DateTime(2010, 12, 1, 10, 0, 0), 36.81);
Console.WriteLine("Temperature Information:\n");
string output;
foreach (var item in temperatureInfo)
{
output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F",
item.Key, item.Value);
Console.WriteLine(output);
}
// The example displays output like the following:
// Temperature Information:
//
// Temperature at 2:00 PM on 6/1/2010: 87.5°F
// Temperature at 10:00 AM on 12/1/2010: 36.8°F
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim temperatureInfo As New Dictionary(Of Date, Double)
temperatureInfo.Add(#6/1/2010 2:00PM#, 87.46)
temperatureInfo.Add(#12/1/2010 10:00AM#, 36.81)
Console.WriteLine("Temperature Information:")
Console.WriteLine()
Dim output As String
For Each item In temperatureInfo
output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", _
item.Key, item.Value)
Console.WriteLine(output)
Next
End Sub
End Module
' The example displays the following output:
' Temperature Information:
'
' Temperature at 2:00 PM on 6/1/2010: 87.5°F
' Temperature at 10:00 AM on 12/1/2010: 36.8°F
另請參閱
- 在 .NET 中將類型格式化
- 複合格式
- 標準日期和時間格式字串
- 自訂日期和時間格式字串
- 標準數值格式字串
- 自訂數值格式字串
- 標準 TimeSpan 格式字串
- 自訂 TimeSpan 格式字串
- 列舉格式字串
適用於
Format(IFormatProvider, String, Object, Object)
以兩個指定物件的字串表示,取代字串中的格式項目。 參數提供特定文化特性格式資訊。
public:
static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1);
public static string Format (IFormatProvider? provider, string format, object? arg0, object? arg1);
static member Format : IFormatProvider * string * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object) As String
參數
- provider
- IFormatProvider
物件,提供特定文化特性格式資訊。
- arg0
- Object
要格式化的第一個物件。
- arg1
- Object
要格式化的第二個物件。
傳回
format
的複本,其中的格式項目已由 arg0
和 arg1
的字串表示取代。
例外狀況
format
為 null
。
備註
重要
請不要呼叫 String.Format 方法或使用 複合格式字串,您可以使用「內插字串」(如果您的語言支援它們的話)。 內插字串是包含「插入運算式」的字串。 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。 如需詳細資訊,請參閱內插字串 (C# 參考) 和內插字串 (Visual Basic 參考)。
這個方法會使用 複合格式功能 將兩個運算式轉換成其字串表示,並將這些標記法內嵌在字串中。 在執行轉換時,方法會使用區分文化特性的格式或自訂格式器。 方法會藉 Object 由呼叫其 Tostring (IFormatProvider) 方法,將每個引數轉換成其字串表示,或者,如果物件的對應格式專案包含格式字串,請呼叫其 Tostring (string,IFormatProvider) 方法。 如果這些方法不存在,則會呼叫物件的無參數 ToString 方法。
不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。 相反地,您可以使用提供區分文化特性或自訂格式的物件和包含一或多個格式項目的複合格式字串來呼叫該方法。 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。
如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門和 要呼叫哪個方法?。
適用於
Format(String, Object, Object, Object)
以三個指定物件的字串表示,取代字串中的格式項目。
public:
static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (string format, object arg0, object arg1, object arg2);
public static string Format (string format, object? arg0, object? arg1, object? arg2);
static member Format : string * obj * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String
參數
- arg0
- Object
要格式化的第一個物件。
- arg1
- Object
要格式化的第二個物件。
- arg2
- Object
要格式化的第三個物件。
傳回
format
的複本,其中的格式項目已由 arg0
、arg1
和 arg2
的字串表示取代。
例外狀況
format
為 null
。
備註
重要
請不要呼叫 String.Format 方法或使用 複合格式字串,您可以使用「內插字串」(如果您的語言支援它們的話)。 內插字串是包含「插入運算式」的字串。 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。 如需詳細資訊,請參閱內插字串 (C# 參考) 和內插字串 (Visual Basic 參考)。
這個方法會使用 複合格式化功能 ,將三個運算式的值轉換成其字串表示,並將這些標記法內嵌在字串中。
不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。 相反地,您可以使用包含一或多個格式項目的複合格式字串來呼叫該方法。 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。
如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門和 要呼叫哪個方法?。
範例:格式化三個引數
這個範例會使用 Format(String, Object, Object, Object) 方法來建立字串,以說明 And
具有兩個整數值的布耳運算結果。 請注意,格式字串包含六個格式專案,但是方法的參數清單中只會有三個專案,因為每個專案都是以兩種不同的方式來格式化。
using namespace System;
void main()
{
String^ formatString = " {0,10} ({0,8:X8})\n" +
"And {1,10} ({1,8:X8})\n" +
" = {2,10} ({2,8:X8})";
int value1 = 16932;
int value2 = 15421;
String^ result = String::Format(formatString,
value1, value2, value1 & value2);
Console::WriteLine(result);
}
// The example displays the following output:
// 16932 (00004224)
// And 15421 (00003C3D)
// = 36 (00000024)
string formatString = " {0,10} ({0,8:X8})\n" +
"And {1,10} ({1,8:X8})\n" +
" = {2,10} ({2,8:X8})";
int value1 = 16932;
int value2 = 15421;
string result = String.Format(formatString,
value1, value2, value1 & value2);
Console.WriteLine(result);
// The example displays the following output:
// 16932 (00004224)
// And 15421 (00003C3D)
// = 36 (00000024)
Public Module Example
Public Sub Main()
Dim formatString As String = " {0,10} ({0,8:X8})" + vbCrLf + _
"And {1,10} ({1,8:X8})" + vbCrLf + _
" = {2,10} ({2,8:X8})"
Dim value1 As Integer = 16932
Dim value2 As Integer = 15421
Dim result As String = String.Format(formatString, _
value1, value2, value1 And value2)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 16932 (00004224)
' And 15421 (00003C3D)
' = 36 (00000024)
另請參閱
適用於
Format(IFormatProvider, String, Object, Object, Object)
以三個指定物件的字串表示,取代字串中的格式項目。 參數提供特定文化特性格式資訊。
public:
static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1, object arg2);
public static string Format (IFormatProvider? provider, string format, object? arg0, object? arg1, object? arg2);
static member Format : IFormatProvider * string * obj * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String
參數
- provider
- IFormatProvider
物件,提供特定文化特性格式資訊。
- arg0
- Object
要格式化的第一個物件。
- arg1
- Object
要格式化的第二個物件。
- arg2
- Object
要格式化的第三個物件。
傳回
format
的複本,其中的格式項目已由 arg0
、arg1
和 arg2
的字串表示取代。
例外狀況
format
為 null
。
備註
重要
請不要呼叫 String.Format 方法或使用 複合格式字串,您可以使用「內插字串」(如果您的語言支援它們的話)。 內插字串是包含「插入運算式」的字串。 每個插值的運算式會以運算式的值解析,且在字串指派時,包含在結果字串中。 如需詳細資訊,請參閱內插字串 (C# 參考) 和內插字串 (Visual Basic 參考)。
這個方法會使用 複合格式化功能 ,將三個運算式轉換成其字串表示,並將這些標記法內嵌在字串中。 在執行轉換時,方法會使用區分文化特性的格式或自訂格式器。 方法會藉 Object 由呼叫其 Tostring (IFormatProvider) 方法,將每個引數轉換成其字串表示,或者,如果物件的對應格式專案包含格式字串,請呼叫其 Tostring (string,IFormatProvider) 方法。 如果這些方法不存在,則會呼叫物件的無參數 ToString 方法。
不過,呼叫 String.Format 方法時,不需要將重點放在您要呼叫的特定多載上。 相反地,您可以使用提供區分文化特性或自訂格式的物件和包含一或多個格式項目的複合格式字串來呼叫該方法。 請為每個格式項目指派一個數值索引;第一個索引會從 0 開始。 除了初始字串之外,您的方法呼叫應該具有與其索引值數目相同的其他引數。 例如,其格式項目具有索引 0 和 1 的字串應該有 2 個引數;具有索引 0 到 5 的字串應該有 6 個引數。 然後,語言編譯器會將您的方法呼叫解析為 String.Format 方法的特定多載。
如需使用 String.Format 方法的其他詳細文件,請參閱 String.Format 方法入門和 要呼叫哪個方法?。