不同文化特性的格式化

更新:2007 年 11 月

對於大部分方法,使用字串格式規範其中之一所傳回的值,可以根據目前文化特性或指定的文化特性來動態變更。例如,ToString 方法的多載會接受實作 IFormatProvider 介面的格式提供者。實作這個介面的類別可以指定當做小數和千位分隔符號使用的字元,和貨幣符號的拼法和位置。如果您不使用會接受這個參數的覆寫,ToString 方法將使用目前文化特性所指定的字元。

下列範例使用 CultureInfo 類別來指定 ToString 方法和格式字串將會使用的文化特性。這個程式碼會建立名為 MyCulture 之 CultureInfo 類別的新執行個體,並使用字串 fr-FR 將它初始化為法文文化特性。這個物件將 C 字串格式規範傳遞給 ToString 方法,以產生法國貨幣值。

Dim MyInt As Integer = 100
Dim MyCulture As New CultureInfo("fr-FR")
Dim MyString As String = MyInt.ToString("C", MyCulture)
Console.WriteLine(MyString)
int MyInt = 100;
CultureInfo MyCulture = new CultureInfo("fr-FR");
String MyString = MyInt.ToString("C", MyCulture);
Console.WriteLine(MyString);

前面的程式碼在 Windows Form 表單上顯示時會顯示 100,00 。請注意,主控台環境不支援所有的 Unicode 字元,因此會改而顯示 100,00 ?。

如需所有支援的文化特性的清單,請參閱 CultureInfo 類別。

下列範例說明如何修改與目前執行緒相關的 CultureInfo 物件。這個範例假設美國英文 (en-US) 是與目前執行緒相關的文化特性,並示範如何透過程式碼變更那個文化特性。這個範例也示範如何藉由傳遞修改過的 CultureInfo 至 ToString方法來指定特定文化特性,以及如何傳遞新的 DateTimeFormatInfo 至 ToString 方法。

Dim dt As DateTime = DateTime.Now
Dim dfi As DateTimeFormatInfo = New DateTimeFormatInfo()
Dim ci As CultureInfo = New CultureInfo("de-DE")

' Create a new custom time pattern for demonstration.
dfi.MonthDayPattern = "MM-MMMM, ddd-dddd"

' Use the DateTimeFormat from the culture associated with 
' the current thread.

Console.WriteLine( dt.ToString("d") ) 
Console.WriteLine( dt.ToString("m") )

' Use the DateTimeFormat object from the specific culture passed.
Console.WriteLine( dt.ToString("d", ci ) )

' Use the settings from the DateTimeFormatInfo object passed.
Console.WriteLine( dt.ToString("m", dfi ) )

' Reset the current thread to a different culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("fr-BE")
Console.WriteLine( dt.ToString("d") )
' This example produces the following output:
'       3/27/2008
'       March 27
'       27.03.2008
'       03-March, Thu-Thursday
'       27/03/2008      
DateTime dt = DateTime.Now;
DateTimeFormatInfo dfi = new DateTimeFormatInfo();
CultureInfo ci = new CultureInfo("de-DE");

// Create a new custom time pattern for demonstration.
dfi.MonthDayPattern = "MM-MMMM, ddd-dddd";

// Use the DateTimeFormat from the culture associated with 
// the current thread.
Console.WriteLine( dt.ToString("d") ); 
Console.WriteLine( dt.ToString("m") );

// Use the DateTimeFormat object from the specific culture passed.
Console.WriteLine( dt.ToString("d", ci ) );

// Use the settings from the DateTimeFormatInfo object passed.
Console.WriteLine( dt.ToString("m", dfi ) );

// Reset the current thread to a different culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-BE");
Console.WriteLine( dt.ToString("d") );
// This example produces the following output:
//       3/27/2008
//       March 27
//       27.03.2008
//       03-March, Thu-Thursday
//       27/03/2008

請參閱

參考

System.IFormatProvider

System.Globalization.CultureInfo

其他資源

格式化型別