將對象的值轉換為基於指定格式的字符串,並將其插入到另一個字符串。
名稱 | 說明 | |
---|---|---|
![]() ![]() |
Format(IFormatProvider, String, Object) |
將指定字符串中的一個或多個格式項替換為對應對象的字符串表示形式。 參數提供區域性特定的格式設置信息。 |
![]() ![]() |
Format(IFormatProvider, String, Object, Object) |
將指定字符串中的格式項替換為兩個指定對象的字符串表示形式。 參數提供區域性特定的格式設置信息。 |
![]() ![]() |
Format(IFormatProvider, String, Object, Object, Object) |
將指定字符串中的格式項替換為三個指定對象的字符串表示形式。 參數提供區域性特定的格式設置信息。 |
![]() ![]() |
Format(IFormatProvider, String, Object[]) |
將指定字符串中的格式項替換為指定數組中相應對象的字符串表示形式。 參數提供區域性特定的格式設置信息。 |
![]() ![]() |
Format(String, Object) |
將指定字符串中的一個或多個格式項替換為指定對象的字符串表示形式。 |
![]() ![]() |
Format(String, Object, Object) |
將指定字符串中的格式項替換為兩個指定對象的字符串表示形式。 |
![]() ![]() |
Format(String, Object, Object, Object) |
將指定字符串中的格式項替換為三個指定對象的字符串表示形式。 |
![]() ![]() |
Format(String, Object[]) |
將指定字符串中的格式項替換為指定數組中相應對象的字符串表示形式。 |
使用String.Format如果你需要將對象、 變量或表達式的值插入到另一個字符串。 例如,可以插入的值Decimal值轉換為要顯示給用戶作為單個字符串的字符串︰
Decimal pricePerOunce = 17.36m; 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:C2} per ounce.", pricePerOunce); // Result if current culture is en-US: // The current price is $17.36 per ounce.
除了格式設置,還可以控制對齊方式和間距。
- 將一個字符串插入
-
String.Format開頭后跟一個或多個對象或表達式將轉換為字符串和格式字符串中指定位置處插入一個格式字符串。 例如:
decimal temp = 20.4m; string s = 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.'
你可以有任意多個格式項,並且作為你的對象列表中的任意多個對象想,只要每個格式項的索引對象列表中具有匹配的對象。 你也不必擔心有關的重載,你調用;編譯器將選擇為你是適合的選項。
- 控制格式設置
-
你可以按照使用格式字符串來控制如何格式化對象的格式項中的索引。 例如,{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'
類型支持的數字格式字符串,包括所有數值類型 (同時標准和自定義格式字符串),所有日期和時間 (同時標准和自定義格式字符串) 和時間間隔 (同時標准和自定義格式字符串),所有枚舉類型枚舉類型,和GUIDs。 你還可以向自己的類型添加支持的格式字符串。
- 控制間距
-
你可以定義通過使用以下語法插入到結果字符串的字符串的寬度{0,12},用於插入 12 個字符的字符串。 在這種情況下,第一個對象的字符串表示為右對齊在 12 個字符字段中。 (如果的長度超過 12 個字符的字符串表示形式的第一個對象,不過,首選的字段寬度將被忽略,並且整個字符串插入到結果字符串。)
下面的示例定義一個 6 字符字段以保存字符串"Year"和某些年字符串,以及 15 個字符字段以保存"填充"的字符串和某些填充數據。 請注意,這些字符右對齊的字段中。
int[] years = { 2013, 2014, 2015 }; int[] population = { 1025632, 1105967, 1148203 }; String s = String.Format("{0,6} {1,15}\n\n", "Year", "Population"); for(int index = 0; index < years.Length; index++) s += String.Format("{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
- 控制對齊方式
-
默認情況下,字符串是右對齊,其字段中如果指定字段寬度。 若要左對齊字符串字段中的,你作為開頭的字段寬度帶一個負號,如{0,-12}定義 12 個字符右對齊字段。
下面的示例類似於前一個,但在於它左對齊標簽和數據。
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]); // Result: // Year Population // // 2013 1,025,632 // 2014 1,105,967 // 2015 1,148,203
String.Format使用復合格式設置功能。 有關詳細信息,請參閱復合格式設置。
選擇重載方法的其他指南,請參閱請勿調用的方法?
- String String.Format(String format, Object arg0)
-
格式項替換的字符串表示形式指定的對象 (示例)。
- String String.Format(String format, Object arg0, Object arg1)
-
格式項替換的字符串表示形式兩個指定對象 (示例)。
- String String.Format(String format, Object arg0, Object arg1, Object arg2)
-
格式項替換的字符串表示形式三個指定對象 (示例)。
- String String.Format(String format, params Object[] args)
-
格式項替換的字符串表示形式指定數組中相應對象 (示例)。
- String String.Format(IFormatProvider provider, String format, params Object[] args)
-
格式項替換的字符串表示形式指定數組中相應對象並使用指定的區域性特定格式設置信息 (示例) 或自定義格式設置信息 (示例)。
例外 |
條件 |
由引發 |
---|---|---|
format 為 null。 |
所有重載。 |
|
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},一個格式字符串和參數列表有三個項。
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 the following output: // At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
格式項具有此語法︰
{ index[,alignment][ :formatString] }
括號表示可選元素。 括號和右大括號是必需的。 (包括文本左或右大括號中的格式字符串,請參閱中的"轉義大括號"一節復合格式設置文章。)
例如,可能貨幣值的格式的格式項將出現如下︰
格式項具有以下元素︰
- 索引
-
字符串表示形式,則為參數的從零開始索引包含在字符串中的此位置。 如果此參數為null,將字符串中的此位置包含一個空字符串。
- 對齊方式
-
可選。 一個帶符號的整數,指示將它插入自變量以及它是右對齊 (正整數) 還是左對齊 (負整數) 到字段的總長度。 如果省略對齊,在具有任何前導空格或尾隨空格的字段中插入的字符串表示形式相應的自變量。
如果的值對齊方式小於參數要插入的長度對齊方式將被忽略,並且長度的字符串表示形式自變量用作字段寬度。
- 格式說明符
-
可選。 一個字符串,指定相應的自變量的結果字符串的格式。 如果省略formatString,相應的自變量的無參數ToString調用方法來生成其字符串表示形式。 如果指定formatString,格式項引用該參數必須實現IFormattable接口。 支持格式字符串的類型包括︰
-
整型和浮點型的所有類型。 (See 標准數字格式字符串 and 自定義數字格式字符串.)
-
DateTime 和 DateTimeOffset。 (See 標准日期和時間格式字符串 and 自定義日期和時間格式字符串.)
-
所有枚舉類型。 (請參閱枚舉格式字符串。)
-
TimeSpan 值。 (See 標准 TimeSpan 格式字符串 and 自定義的 TimeSpan 格式字符串.)
-
GUID。 (請參閱Guid.ToString(String)方法。)
但請注意任何自定義類型可以實現IFormattable或擴展現有類型的IFormattable實現。
-
下面的示例使用alignment和formatString自變量才能生成格式化的輸出。
using System; public class Example { public static void Main() { // 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 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; foreach (var 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 %
格式項按順序處理從該字符串的開頭。 每個格式項都有對應於一個對象,該方法的自變量列表中的索引。 Format方法檢索自變量和派生其字符串表示形式,如下所示︰
-
如果參數是null,則該方法插入String.Empty到結果字符串。
-
如果調用Format(IFormatProvider, String, Object[])重載和provider參數實現ICustomFormatter接口,自變量傳遞給provider對象的ICustomFormatter.Format(String, Object, IFormatProvider)方法。 如果格式項包含formatString自變量,它作為第一個參數傳遞給方法。 如果ICustomFormatter能提供格式設置服務實現,則它將返回的字符串表示形式自變量; 否則,它將返回null和執行下一步的步驟。
-
如果參數實現IFormattable接口,其IFormattable.ToString調用實現。
-
自變量的無參數ToString方法,重寫或繼承自Object類,則調用。
有關示例,截獲對的調用ICustomFormatter.Format方法,你可以查看哪些信息和Format方法傳遞到格式設置方法,以每個格式項在復合格式字符串中,請參閱示例 7: 截距提供程序和羅馬數字格式化程序。
Format方法拋出異常FormatException異常索引項的索引是否大於或等於自變量列表中的參數的數目。 但是,format可以包括多個格式項不是有自變量,只要多個格式項都具有相同的索引。 在調用Format(String, Object)在以下示例中,自變量列表的方法具有單個參數,但該格式字符串包含兩個格式項︰ 一個顯示的一個數字,十進制值,另一個顯示其十六進制值。
public class Example { public static void Main() { 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
通常,對象自變量列表中的將轉換為其字符串表示形式返回使用當前區域性的約定CultureInfo.CurrentCulture屬性。 您可以通過調用的重載之一來控制此行為Format包括provider參數。 provider參數是IFormatProvider實現,提供用於中等格式的自定義和區域性特定格式設置信息處理。
IFormatProvider接口具有一個成員, GetFormat,即負責返回提供的格式設置信息的對象。 .NET Framework 具有三個IFormatProvider提供區域性特定格式設置的實現︰
-
CultureInfo。 其GetFormat方法返回特定於區域性的NumberFormatInfo設置數字值和區域性特定格式的對象DateTimeFormatInfo格式化日期和時間值的對象。
-
DateTimeFormatInfo它用於特定於區域性的格式設置的日期和時間值。 其GetFormat方法返回它自身。
-
NumberFormatInfo它用於區域性特定格式的數字值。 其GetFormat屬性返回它自身。
你還可以調用的重載任意Format具有方法provider參數Format(IFormatProvider, String, Object[])重載以執行自定義格式設置操作。 例如,您無法設置整數格式作為一個標識號或電話號碼。 若要執行自定義格式設置,你provider自變量必須同時實現IFormatProvider和ICustomFormatter接口。 當Format方法傳遞ICustomFormatter實現作為provider自變量,Format方法調用其IFormatProvider.GetFormat實現請求的類型的對象和ICustomFormatter。 然后,它調用返回ICustomFormatter對象的Format方法來設置格式復合字符串中的每個格式項傳遞給它。
有關提供自定義格式設置解決方案的詳細信息,請參閱如何:定義和使用自定義數值格式提供程序和ICustomFormatter。 將整數轉換為格式化自定義數字示例,請參閱示例 6︰ 自定義格式設置操作。 將無符號的字節轉換為羅馬數字示例,請參閱示例 7: 截距提供程序和羅馬數字格式化程序。
下面的示例使用Format(String, Object)方法將字符串中間的一個人的年齡。
using System; [assembly: CLSCompliant(true)] public class Example { public static void Main() { 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.
此示例使用Format(String, Object, Object)方法以顯示時間和溫度數據存儲在一個泛型Dictionary<TKey, TValue>對象。 請注意,格式字符串將有三個格式項,盡管有只有兩個要格式化的對象。 這是因為在列表中 (日期和時間值) 的第一個對象由兩個格式項︰ 第一個格式項目將顯示時間和第二個顯示的日期。
using System; using System.Collections.Generic; public class Example { public static void Main() { 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 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
此示例使用Format(String, Object, Object, Object)方法來創建的字符串,演示了一個布爾值的結果And具有兩個整數值的操作。 請注意,格式字符串包括六個格式項,但該方法具有在其參數列表中,只有三個項,因為每個項格式化兩個不同的方式。
using System; public class Example { public static 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)
此示例創建一個字符串,包含在特定日期的最高價和最溫度上的數據。 復合格式字符串,並且在 C# 示例中的五個格式項六個 in Visual Basic 示例。 兩個格式項定義其對應的值的字符串表示形式的寬度和第一個格式項還包括標准日期和時間格式字符串。
using System; public class Example { public static void Main() { 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 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 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
此示例使用Format(IFormatProvider, String, Object[])方法以通過使用幾種不同區域性中顯示的字符串表示形式某些日期和時間值和數值。
using System; using System.Globalization; public class Example { public static void Main() { 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) { CultureInfo culture = new 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
此示例定義一個整數值的格式設置為窗體 x xxxxx xx 的客戶帳戶數字的格式提供。
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.
此示例定義一個自定義格式提供程序實現ICustomFormatter和IFormatProvider接口,以便執行兩項操作︰
-
它顯示的參數傳遞給其ICustomFormatter.Format實現。 這使我們能夠查看哪些參數Format(IFormatProvider, String, Object[])方法傳遞到每個對象,它將嘗試設置格式的自定義格式設置實現。 調試你的應用程序時,這很有用。
-
如果要設置格式的對象是一個無符號的字節值,是要通過使用"R"標准格式字符串設置格式,自定義格式化程序設置為羅馬數字格式的數字值。
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, 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
- .NET Framework
-
中支持所有重載︰ 4.5、 4、 3.5、 3.0、 2.0、 1.1、 1.0
- .NET Framework Client Profile
-
中支持所有重載︰ 4、 3.5 SP1
- 可移植類庫
-
僅Format(String, Object[])和Format(IFormatProvider, String, Object[])支持
- 適用於 Windows 應用商店應用的 .NET
-
僅Format(String, Object[])和Format(IFormatProvider, String, Object[])支持在 Windows 8 中
-
有關整型和浮點型的所有類型,請參閱標准數字格式字符串和自定義數字格式字符串。
-
日期和時間值,請參閱標准日期和時間格式字符串和自定義日期和時間格式字符串。
-
枚舉值,請參閱枚舉格式字符串。
-
有關Guid值,請參閱備注部分的Guid.ToString(String)引用頁。
格式項的常規語法是︰
{index[,alignment][: formatString]}
其中對齊是一個有符號的整數,它定義的字段寬度。 如果此值為負,則字段中的文本是左對齊。 如果它為正,文本為右對齊。
所有標准數字格式字符串except"D"(它們使用僅包含整數)、"G"、"R"和"X"允許在結果字符串中定義的十進制位數的精度說明符。 下面的示例使用標准數字格式字符串來控制結果字符串中的十進制數字個數。
using System; public class Example { public static void Main() { 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 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"格式說明符來控制在結果字符串中,如以下示例所示的十進制數字個數。
默認情況下,格式設置操作將僅顯示非零整數位。 如果你要設置格式的整數,可以使用精度說明符"D"與"X"標准格式字符串來控制的數字位數。
using System; public class Example { public static void Main() { 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
要通過使用"0"來生成具有指定數字的整數位數的結果字符串的整數或帶前導零的浮點數可以填充自定義數字格式說明符,如下面的示例所示。
using System; public class Example { public static void Main() { 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
沒有實際限制。 第二個參數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);
但是,即使轉義大括號是輕松 misinterpreted。 我們建議你在格式列表中包含大括號和格式項用於將它們插在結果字符串中,如以下示例所示。
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.", nOpen, "{", nClose, "}");
異常的最常見原因是,不會與格式列表中的對象相對應的格式項的索引。 通常,這表示已 misnumbered 格式項的索引,或您忘記了在格式列表中包含的對象。 有時,例外情況是拼寫錯誤; 結果例如,典型的錯誤是錯誤地鍵入"["(左的括號) 而不是"{"(左大括號)。
例如,下面的代碼引發FormatException異常︰
using System; using System.Collections.Generic; public class Example { public static void Main() { 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); } }
這是編譯器重載解析出現問題。 因為編譯器不能將整數的數組轉換為一個對象數組,它將整數的數組視為單個參數,因此,它調用Format(String, Object)方法。 將引發異常,因為有四個格式項,但僅格式列表中的單個項。
由於既不 Visual Basic 和 C# 可以將一個整數數組轉換為一個對象數組,你必須執行轉換,然后再調自己Format(String, Object[])方法。 下面的示例提供一個實現。
using System; using System.Collections.Generic; public class Example { public static void Main() { 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); } }