CultureInfo CultureInfo CultureInfo CultureInfo Class

定義

提供有關特定文化特性 (Culture) 的資訊 (文化特性在 Unmanaged 程式碼開發中稱為「地區設定」)。Provides information about a specific culture (called a locale for unmanaged code development). 這項資訊包含文化特性的名稱、書寫系統、使用的曆法、字串的排序次序,以及日期和數字的格式。The information includes the names for the culture, the writing system, the calendar used, the sort order of strings, and formatting for dates and numbers.

public ref class CultureInfo : ICloneable, IFormatProvider
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class CultureInfo : ICloneable, IFormatProvider
type CultureInfo = class
    interface ICloneable
    interface IFormatProvider
Public Class CultureInfo
Implements ICloneable, IFormatProvider
繼承
CultureInfoCultureInfoCultureInfoCultureInfo
屬性
實作

範例

下列範例示範如何建立CultureInfo西班牙文 (西班牙) 與國際排序,而另一個物件CultureInfo傳統排序物件。The following example shows how to create a CultureInfo object for Spanish (Spain) with the international sort and another CultureInfo object with the traditional sort.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
int main()
{
   
   // Creates and initializes the CultureInfo which uses the international sort.
   CultureInfo^ myCIintl = gcnew CultureInfo( "es-ES",false );
   
   // Creates and initializes the CultureInfo which uses the traditional sort.
   CultureInfo^ myCItrad = gcnew CultureInfo( 0x040A,false );
   
   // Displays the properties of each culture.
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "PROPERTY", "INTERNATIONAL", "TRADITIONAL" );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "CompareInfo", myCIintl->CompareInfo, myCItrad->CompareInfo );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "DisplayName", myCIintl->DisplayName, myCItrad->DisplayName );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "EnglishName", myCIintl->EnglishName, myCItrad->EnglishName );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "IsNeutralCulture", myCIintl->IsNeutralCulture, myCItrad->IsNeutralCulture );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "IsReadOnly", myCIintl->IsReadOnly, myCItrad->IsReadOnly );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "LCID", myCIintl->LCID, myCItrad->LCID );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "Name", myCIintl->Name, myCItrad->Name );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "NativeName", myCIintl->NativeName, myCItrad->NativeName );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "Parent", myCIintl->Parent, myCItrad->Parent );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "TextInfo", myCIintl->TextInfo, myCItrad->TextInfo );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "ThreeLetterISOLanguageName", myCIintl->ThreeLetterISOLanguageName, myCItrad->ThreeLetterISOLanguageName );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "ThreeLetterWindowsLanguageName", myCIintl->ThreeLetterWindowsLanguageName, myCItrad->ThreeLetterWindowsLanguageName );
   Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "TwoLetterISOLanguageName", myCIintl->TwoLetterISOLanguageName, myCItrad->TwoLetterISOLanguageName );
   Console::WriteLine();
   
   // Compare two strings using myCIintl -> 
   Console::WriteLine( "Comparing \"llegar\" and \"lugar\"" );
   Console::WriteLine( "   With myCIintl -> CompareInfo -> Compare: {0}", myCIintl->CompareInfo->Compare( "llegar", "lugar" ) );
   Console::WriteLine( "   With myCItrad -> CompareInfo -> Compare: {0}", myCItrad->CompareInfo->Compare( "llegar", "lugar" ) );
}

/*
This code produces the following output.

PROPERTY                       INTERNATIONAL                                  TRADITIONAL              
CompareInfo                    CompareInfo - es-ES                            CompareInfo - es-ES_tradnl
DisplayName                    Spanish (Spain)                                Spanish (Spain)          
EnglishName                    Spanish (Spain, International Sort)            Spanish (Spain, Traditional Sort)
IsNeutralCulture               False                                          False                    
IsReadOnly                     False                                          False                    
LCID                           3082                                           1034                     
Name                           es-ES                                          es-ES                    
NativeName                     Español (España, alfabetización internacional) Español (España, alfabetización tradicional)
Parent                         es                                             es                       
TextInfo                       TextInfo - es-ES                               TextInfo - es-ES_tradnl  
ThreeLetterISOLanguageName     spa                                            spa                      
ThreeLetterWindowsLanguageName ESN                                            ESP                      
TwoLetterISOLanguageName       es                                             es                       

Comparing "llegar" and "lugar"
   With myCIintl -> CompareInfo -> Compare: -1
   With myCItrad -> CompareInfo -> Compare: 1

*/
using System;
using System.Collections;
using System.Globalization;

public class SamplesCultureInfo
{

   public static void Main()
   {

      // Creates and initializes the CultureInfo which uses the international sort.
      CultureInfo myCIintl = new CultureInfo("es-ES", false);

      // Creates and initializes the CultureInfo which uses the traditional sort.
      CultureInfo myCItrad = new CultureInfo(0x040A, false);

      // Displays the properties of each culture.
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "PROPERTY", "INTERNATIONAL", "TRADITIONAL");
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "CompareInfo", myCIintl.CompareInfo, myCItrad.CompareInfo);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "DisplayName", myCIintl.DisplayName, myCItrad.DisplayName);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "EnglishName", myCIintl.EnglishName, myCItrad.EnglishName);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "IsNeutralCulture", myCIintl.IsNeutralCulture, myCItrad.IsNeutralCulture);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "IsReadOnly", myCIintl.IsReadOnly, myCItrad.IsReadOnly);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "LCID", myCIintl.LCID, myCItrad.LCID);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "Name", myCIintl.Name, myCItrad.Name);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "NativeName", myCIintl.NativeName, myCItrad.NativeName);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "Parent", myCIintl.Parent, myCItrad.Parent);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "TextInfo", myCIintl.TextInfo, myCItrad.TextInfo);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "ThreeLetterISOLanguageName", myCIintl.ThreeLetterISOLanguageName, myCItrad.ThreeLetterISOLanguageName);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "ThreeLetterWindowsLanguageName", myCIintl.ThreeLetterWindowsLanguageName, myCItrad.ThreeLetterWindowsLanguageName);
      Console.WriteLine("{0,-31}{1,-47}{2,-25}", "TwoLetterISOLanguageName", myCIintl.TwoLetterISOLanguageName, myCItrad.TwoLetterISOLanguageName);
      Console.WriteLine();

      // Compare two strings using myCIintl.
      Console.WriteLine("Comparing \"llegar\" and \"lugar\"");
      Console.WriteLine("   With myCIintl.CompareInfo.Compare: {0}", myCIintl.CompareInfo.Compare("llegar", "lugar"));
      Console.WriteLine("   With myCItrad.CompareInfo.Compare: {0}", myCItrad.CompareInfo.Compare("llegar", "lugar"));

   }

}

/*
This code produces the following output.

PROPERTY                       INTERNATIONAL                                  TRADITIONAL              
CompareInfo                    CompareInfo - es-ES                            CompareInfo - es-ES_tradnl
DisplayName                    Spanish (Spain)                                Spanish (Spain)          
EnglishName                    Spanish (Spain, International Sort)            Spanish (Spain, Traditional Sort)
IsNeutralCulture               False                                          False                    
IsReadOnly                     False                                          False                    
LCID                           3082                                           1034                     
Name                           es-ES                                          es-ES                    
NativeName                     Español (España, alfabetización internacional) Español (España, alfabetización tradicional)
Parent                         es                                             es                       
TextInfo                       TextInfo - es-ES                               TextInfo - es-ES_tradnl  
ThreeLetterISOLanguageName     spa                                            spa                      
ThreeLetterWindowsLanguageName ESN                                            ESP                      
TwoLetterISOLanguageName       es                                             es                       

Comparing "llegar" and "lugar"
   With myCIintl.CompareInfo.Compare: -1
   With myCItrad.CompareInfo.Compare: 1

*/
Imports System
Imports System.Collections
Imports System.Globalization

Module Module1

    Public Sub Main()

        ' Creates and initializes the CultureInfo which uses the international sort.
        Dim myCIintl As New CultureInfo("es-ES", False)

        ' Creates and initializes the CultureInfo which uses the traditional sort.
        Dim myCItrad As New CultureInfo(&H40A, False)

        ' Displays the properties of each culture.
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "PROPERTY", "INTERNATIONAL", "TRADITIONAL")
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "CompareInfo", myCIintl.CompareInfo, myCItrad.CompareInfo)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "DisplayName", myCIintl.DisplayName, myCItrad.DisplayName)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "EnglishName", myCIintl.EnglishName, myCItrad.EnglishName)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "IsNeutralCulture", myCIintl.IsNeutralCulture, myCItrad.IsNeutralCulture)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "IsReadOnly", myCIintl.IsReadOnly, myCItrad.IsReadOnly)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "LCID", myCIintl.LCID, myCItrad.LCID)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "Name", myCIintl.Name, myCItrad.Name)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "NativeName", myCIintl.NativeName, myCItrad.NativeName)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "Parent", myCIintl.Parent, myCItrad.Parent)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "TextInfo", myCIintl.TextInfo, myCItrad.TextInfo)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "ThreeLetterISOLanguageName", myCIintl.ThreeLetterISOLanguageName, myCItrad.ThreeLetterISOLanguageName)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "ThreeLetterWindowsLanguageName", myCIintl.ThreeLetterWindowsLanguageName, myCItrad.ThreeLetterWindowsLanguageName)
        Console.WriteLine("{0,-31}{1,-47}{2,-25}", "TwoLetterISOLanguageName", myCIintl.TwoLetterISOLanguageName, myCItrad.TwoLetterISOLanguageName)
        Console.WriteLine()

        ' Compare two strings using myCIintl.
        Console.WriteLine("Comparing ""llegar"" and ""lugar""")
        Console.WriteLine("   With myCIintl.CompareInfo.Compare: {0}", myCIintl.CompareInfo.Compare("llegar", "lugar"))
        Console.WriteLine("   With myCItrad.CompareInfo.Compare: {0}", myCItrad.CompareInfo.Compare("llegar", "lugar"))

    End Sub 'Main 



'This code produces the following output.
'
'PROPERTY                       INTERNATIONAL                                  TRADITIONAL              
'CompareInfo                    CompareInfo - es-ES                            CompareInfo - es-ES_tradnl
'DisplayName                    Spanish (Spain)                                Spanish (Spain)          
'EnglishName                    Spanish (Spain, International Sort)            Spanish (Spain, Traditional Sort)
'IsNeutralCulture               False                                          False                    
'IsReadOnly                     False                                          False                    
'LCID                           3082                                           1034                     
'Name                           es-ES                                          es-ES                    
'NativeName                     Español (España, alfabetización internacional) Español (España, alfabetización tradicional)
'Parent                         es                                             es                       
'TextInfo                       TextInfo - es-ES                               TextInfo - es-ES_tradnl  
'ThreeLetterISOLanguageName     spa                                            spa                      
'ThreeLetterWindowsLanguageName ESN                                            ESP                      
'TwoLetterISOLanguageName       es                                             es                       
'
'Comparing "llegar" and "lugar"
'   With myCIintl.CompareInfo.Compare: -1
'   With myCItrad.CompareInfo.Compare: 1

End Module

備註

CultureInfo類別提供特定文化特性資訊,例如語言、 次語言、 國家/地區、 行事曆和特定文化特性相關聯的慣例。The CultureInfo class provides culture-specific information, such as the language, sublanguage, country/region, calendar, and conventions associated with a particular culture. 這個類別也會提供存取的特定文化特性的執行個體DateTimeFormatInfoNumberFormatInfoCompareInfo,和TextInfo物件。This class also provides access to culture-specific instances of the DateTimeFormatInfo, NumberFormatInfo, CompareInfo, and TextInfo objects. 這些物件包含特定文化特性的作業,例如大小寫、 格式化日期和數字和比較字串所需的資訊。These objects contain the information required for culture-specific operations, such as casing, formatting dates and numbers, and comparing strings. CultureInfo類別可供直接或間接類別,可格式化、 剖析,或處理特定文化特性的資料,例如StringDateTimeDateTimeOffset,和數字的類型。The CultureInfo class is used either directly or indirectly by classes that format, parse, or manipulate culture-specific data, such as String, DateTime, DateTimeOffset, and the numeric types.

本節內容:In this section:

文化特性名稱和識別碼 Culture names and identifiers
非變異、 中性和特定文化特性 Invariant, neutral, and specific cultures
自訂文化特性 Custom cultures
動態的文化特性的資料 Dynamic culture data
CultureInfo 和文化特性的資料目前 UI 文化特性與目前的文化特性 CultureInfo and cultural data The current culture and current UI culture
取得所有文化特性 Getting all cultures
文化特性和執行緒 Culture and threads
文化特性和應用程式網域 Culture and application domains
文化特性和以工作為基礎的非同步作業 Culture and task-based asynchronous operations
CultureInfo 物件的序列化 CultureInfo object serialization
控制台會覆寫 Control Panel overrides
替代排序次序 Alternate sort orders
文化特性和 Windows 應用程式Culture and Windows apps

文化特性名稱和識別碼Culture names and identifiers

CultureInfo類別會指定每個文化特性,根據 RFC 4646 的唯一名稱。The CultureInfo class specifies a unique name for each culture, based on RFC 4646. 名稱是與語言相關聯的 ISO 639 兩個字母小寫文化特性代碼和國家/地區或區域相關聯的 ISO 3166 兩個字母大寫子文化特性代碼的組合。The name is a combination of an ISO 639 two-letter lowercase culture code associated with a language and an ISO 3166 two-letter uppercase subculture code associated with a country or region. 此外,針對目標應用程式.NET Framework 4.NET Framework 4或更新版本,而且正在執行 Windows 10 或更新版本中,對應至有效 BCP-47 語言標記支援的文化特性名稱。In addition, for apps that target .NET Framework 4.NET Framework 4 or later and are running under Windows 10 or later, culture names that correspond to valid BCP-47 language tags are supported.

注意

當文化特性名稱傳遞至類別建構函式或方法這類CreateSpecificCultureCultureInfo,其大小寫不重要。When a culture name is passed to a class constructor or a method such as CreateSpecificCulture or CultureInfo, its case is not significant.

格式為文化特性名稱,根據 RFC 4646 languagecode2>-country/regioncode2,其中languagecode2是兩個字母的語言代碼並country/regioncode2是兩個字母子文化特性的程式碼。The format for the culture name based on RFC 4646 is languagecode2>-country/regioncode2, where languagecode2 is the two-letter language code and country/regioncode2 is the two-letter subculture code. 範例包括 JA-JP 日文 (日本) 和 EN-US,適用於英文 (美國)。Examples include ja-JP for Japanese (Japan) and en-US for English (United States). 在兩個字母的語言程式碼不提供的情況下,會使用衍生自 ISO 639-2 三個字母代碼。In cases where a two-letter language code is not available, a three-letter code derived from ISO 639-2 is used.

請注意,某些文化特性名稱也會指定 ISO 15924。Note that some culture names also specify an ISO 15924 script. 比方說,Cyrl 指定斯拉夫文的指令碼和 Latn 指定英文的指令碼。For example, Cyrl specifies the Cyrillic script and Latn specifies the Latin script. 文化特性名稱,其中包含指令碼會使用模式languagecode2-scripttag-country/regioncode2A culture name that includes a script uses the pattern languagecode2-scripttag-country/regioncode2. 這種文化特性名稱的範例是 uz 代表烏茲別克文 (斯拉夫,烏茲別克)。An example of this type of culture name is uz-Cyrl-UZ for Uzbek (Cyrillic, Uzbekistan). 在 Windows 作業系統在 Windows Vista 之前,文化特性名稱,其中包含指令碼會使用模式languagecode2-country/regioncode2 - scripttag,比方說,uz-UZ-Cyrl 烏茲別克文 (斯拉夫,烏茲別克)。On Windows operating systems before Windows Vista, a culture name that includes a script uses the pattern languagecode2-country/regioncode2-scripttag, for example, uz-UZ-Cyrl for Uzbek (Cyrillic, Uzbekistan).

中性文化特性是由兩個字母小寫字母的語言程式碼指定。A neutral culture is specified by only the two-letter lowercase language code. 比方說,fr 指定中性文化特性的法文和德國德文指定中性文化特性。For example, fr specifies the neutral culture for French, and de specifies the neutral culture for German.

注意

有兩個相互抵觸此規則的文化特性名稱。There are two culture names that contradict this rule. 中文 (簡體)、 名為 Zh-hans 和中文 (繁體)、 名為 Zh-hant,文化特性是中性文化特性。The cultures Chinese (Simplified), named zh-Hans, and Chinese (Traditional), named zh-Hant, are neutral cultures. 文化特性名稱代表目前的標準,而應使用,除非您有使用的舊名稱 ZH-CHS 和 ZH-CHT 的原因。The culture names represent the current standard and should be used unless you have a reason for using the older names zh-CHS and zh-CHT.

文化特性識別項是標準的國際數字縮寫,來唯一識別其中已安裝的文化特性所需的元件。A culture identifier is a standard international numeric abbreviation and has the components necessary to uniquely identify one of the installed cultures. 您的應用程式可以使用預先定義的文化特性識別項,或定義自訂的識別項。Your application can use predefined culture identifiers or define custom identifiers.

某些預先定義的文化特性名稱,這和中的其他類別所使用的識別項System.Globalization命名空間。Certain predefined culture names and identifiers are used by this and other classes in the System.Globalization namespace. 適用於 Windows 系統的詳細的文化特性資訊,請參閱語言標記中的資料行Windows 所支援的語言/地區名稱清單For detailed culture information for Windows systems, see the Language tag column in the list of language/region names supported by Windows. 文化特性名稱遵循所定義的標準BCP 47Culture names follow the standard defined by BCP 47.

請記住的文化特性名稱和識別碼,代表只可以在特定電腦找到的文化特性的子集。Remember that the culture names and identifiers represent only a subset of cultures that can be found on a particular computer. Windows 版本或 service pack 可以變更可用的文化特性。Windows versions or service packs can change the available cultures. 應用程式將使用的自訂文化特性CultureAndRegionInfoBuilder類別。Applications add custom cultures using the CultureAndRegionInfoBuilder class. 使用者會新增自己自訂的文化特性,使用 Microsoft Locale Builder 工具。Users add their own custom cultures using the Microsoft Locale Builder tool. Microsoft Locale Builder 以 managed 程式碼使用CultureAndRegionInfoBuilder類別。Microsoft Locale Builder is written in managed code using the CultureAndRegionInfoBuilder class.

數個不同的名稱是密切相關聯的文化特性,值得注意的是將下列類別成員相關聯的名稱:Several distinct names are closely associated with a culture, notably the names associated with the following class members:

非變異、 中性和特定文化特性Invariant, neutral, and specific cultures

文化特性通常分為三個集合: 而異的文化特性、 中性文化特性和特定文化特性。The cultures are generally grouped into three sets: invariant cultures, neutral cultures, and specific cultures.

不區分文化特性的文化特性而異。An invariant culture is culture-insensitive. 您的應用程式指定文化特性而異,依名稱使用空字串 ("") 或依其識別項。Your application specifies the invariant culture by name using an empty string ("") or by its identifier. InvariantCulture 定義文化特性而異的執行個體。InvariantCulture defines an instance of the invariant culture. 相關聯的英文語言使用,但不是能搭配任何國家/地區。It is associated with the English language but not with any country/region. 在幾乎任何方法中使用Globalization需要文化特性的命名空間。It is used in almost any method in the Globalization namespace that requires a culture.

中性文化特性是相關聯的文化特性使用的語言,但是不會與國家/地區。A neutral culture is a culture that is associated with a language but not with a country/region. 特定文化特性是一種語言和國家/地區相關聯的文化特性。A specific culture is a culture that is associated with a language and a country/region. 比方說,fr 是法文的文化特性的中性名稱,並為 FR-FR 是特定的法文 (法國) 文化特性的名稱。For example, fr is the neutral name for the French culture, and fr-FR is the name of the specific French (France) culture. 請注意,中文 (簡體) 和中文 (繁體) 也會被視為中性文化特性。Note that Chinese (Simplified) and Chinese (Traditional) are also considered neutral cultures.

建立的執行個體CompareInfo中性文化特性不建議,因為它所包含的資料是任意的類別。Creating an instance of a CompareInfo class for a neutral culture is not recommended because the data it contains is arbitrary. 若要顯示和排序資料,請指定語言和區域。To display and sort data, specify both the language and region. 此外,Name屬性CompareInfo中性文化特性,傳回的國家/地區並不包括地區所建立的物件。Additionally, the Name property of a CompareInfo object created for a neutral culture returns only the country and does not include the region.

定義的文化特性具有的階層,其中的父代特定文化特性是中性文化特性,而是中性文化特性的父代是文化特性而異。The defined cultures have a hierarchy in which the parent of a specific culture is a neutral culture and the parent of a neutral culture is the invariant culture. Parent屬性包含特定文化特性相關聯的中性文化特性。The Parent property contains the neutral culture associated with a specific culture. 應該要定義自訂的文化特性Parent符合此模式中的屬性。Custom cultures should define the Parent property in conformance with this pattern.

如果特定文化特性的資源不會在作業系統中可用的則會使用相關聯的中性文化特性的資源。If the resources for a specific culture are not available in the operating system, the resources for the associated neutral culture are used. 如果無法使用中性文化特性的資源時,會使用內嵌於主要組件中的資源。If the resources for the neutral culture are not available, the resources embedded in the main assembly are used. 如需有關資源後援處理序的詳細資訊,請參閱 < 封裝和部署資源For more information on the resource fallback process, see Packaging and Deploying Resources.

Windows API 中的地區設定的清單是稍微不同的.NET Framework 所支援的文化特性的清單。The list of locales in the Windows API is slightly different from the list of cultures supported by the .NET Framework. 如果需要與 Windows 的互通性,比方說,透過 p/invoke 機制中,應用程式應該使用特定文化特性所定義的作業系統。If interoperability with Windows is required, for example, through the p/invoke mechanism, the application should use a specific culture that is defined for the operating system. 使用特定文化特性可確保對等的 Windows 地區設定,這識別與相同的地區設定識別碼的一致性LCIDUse of the specific culture ensures consistency with the equivalent Windows locale, which is identified with a locale identifier that is the same as LCID.

ADateTimeFormatInfoNumberFormatInfo可以建立只而異的文化特性或特定文化特性,而非中性文化特性。A DateTimeFormatInfo or a NumberFormatInfo can be created only for the invariant culture or for specific cultures, not for neutral cultures.

如果DateTimeFormatInfo.CalendarTaiwanCalendarThread.CurrentCulture不設定為 ZH-TW,然後DateTimeFormatInfo.NativeCalendarNameDateTimeFormatInfo.GetEraName,和DateTimeFormatInfo.GetAbbreviatedEraName傳回空字串 ("")。If DateTimeFormatInfo.Calendar is the TaiwanCalendar but the Thread.CurrentCulture is not set to zh-TW, then DateTimeFormatInfo.NativeCalendarName, DateTimeFormatInfo.GetEraName, and DateTimeFormatInfo.GetAbbreviatedEraName return an empty string ("").

自訂文化特性Custom cultures

除了預先定義的文化特性支援的 Windows 作業系統和.NET Framework 時,.NET Framework 支援三種類型的自訂文化特性:In addition to the predefined cultures supported by the Windows operating system and the .NET Framework, the .NET Framework supports three types of custom cultures:

  • 補充的文化特性可在 Windows 或.NET Framework 中的新文化特性。New cultures that supplement the cultures available in Windows or the .NET Framework. 例如,應用程式無法安裝CultureInfo代表 fj-fj 將 (或 Fijan (斐濟)) 文化特性的系統上的物件。For example, an application could install a CultureInfo object that represents the fj-FJ (or Fijan (Fiji)) culture on a system.

  • 其屬性會不同於標準 Windows 和.NET Framework 所支援的文化特性的屬性取代的文化特性。Replacement cultures whose properties are different from the properties of the standard cultures supported by Windows and the .NET Framework.

  • 標準使用者的文化特性會覆寫。Standard cultures with user overrides. 使用者可以使用地區和語言應用程式控制台自訂現有文化特性的屬性值。The user can use the Region and Language application in Control Panel to customize an existing culture's property values.

注意

您可以使用CultureAndRegionInfoBuilder類別來定義、 儲存及註冊自訂的文化特性,來補充或取代現有的文化特性。You can use the CultureAndRegionInfoBuilder class to define, save, and register custom cultures that either supplement or replace existing cultures. CultureAndRegionInfoBuilder.Save方法會建立可用來在目標系統上安裝自訂的文化特性的地區設定資料標記語言 (LDML) 檔案。The CultureAndRegionInfoBuilder.Save method creates a Locale Data Markup Language (LDML) file that can be used to install a custom culture on target systems. 如逐步步驟需使用CultureAndRegionInfoBuilder來建立新的類別或取代的文化特性,請參閱CultureAndRegionInfoBuilder類別主題。For step-by step information on using the CultureAndRegionInfoBuilder class to create a new or replacement culture, see the CultureAndRegionInfoBuilder class topic.

由於.NET Framework 支援自訂文化特性,您應該考慮下列使用特定文化特性的資料時:Because the .NET Framework supports custom cultures, you should consider the following when working with culture-specific data:

  • 自訂文化特性可以有超過預先定義的文化特性的範圍的值。Custom cultures can have values that exceed the ranges of the predefined cultures. 比方說,某些文化特性已久的月份名稱、 未預期的日期或時間格式或其他不尋常的資料。For example, some cultures have unusually long month names, unexpected date or time formats, or other unusual data.

  • 當您在使用者介面中顯示特定文化特性的資料時,您應該採用使用者的自訂項目;例如,使用者可能會想採用 24 小時制或 yyyyMMdd 日期格式。When you display culture-specific data in the user interface, you should respect the user's customizations; for example, the user might want a 24-hour clock or a yyyyMMdd date format.

  • 請記住,自訂文化特性覆寫預設值。Remember that custom cultures override default values. 因此,您無法考慮文化特性資料視為穩定。Therefore, you cannot consider culture data to be stable. 國家/地區名稱、 數字和日期格式和拼字可能在未來變更。Country names, number and date formats, and spellings may change in the future. 如果您想要將區分文化特性的資料,例如要傳遞至日期和時間剖析函式的日期和時間字串序列化,您應該使用區分文化特性或特定。If you want to serialize culture-sensitive data such as date and time strings to be passed to the date and time parsing functions, you should use the invariant culture or a specific .

CultureTypes安裝在系統上的自訂文化特性的屬性值會包含System.Globalization.CultureTypes旗標及自訂的文化特性會被指派LCID屬性值為LOCALE_CUSTOM_UNSPECIFIED(0x1000 控制或 4096)。The CultureTypes property value of custom cultures installed on a system includes the System.Globalization.CultureTypes flag, and custom cultures are assigned an LCID property value of LOCALE_CUSTOM_UNSPECIFIED (0x1000, or 4096). 請注意,從 Windows 10 開始,這個值也會指派給系統定義的文化特性缺少完整文化特性的資料。Note that, starting with Windows 10, this value is also assigned to system-defined cultures that lack complete cultural data.

CultureInfo 和文化特性的資料CultureInfo and cultural data

.NET 衍生其文化特性的資料從各種來源,取決於實作、 平台和版本的其中一個:.NET derives its cultural data from a one of a variety of sources, depending on implementation, platform, and version:

  • 在.NET Framework 3.5 和更早版本中,文化特性的資料是由 Windows 作業系統和.NET Framework 提供。In .NET Framework 3.5 and earlier versions, cultural data is provided by both the Windows operating system and the .NET Framework.

  • 在.NET Framework 4 和更新版本中,由 Windows 作業系統提供文化特性的資料。In .NET Framework 4 and later versions, cultural data is provided by the Windows operating system.

  • 在所有版本的 Windows 上執行的.NET Core,文化特性的資料是由 Windows 作業系統提供。In all versions of .NET Core running on Windows, cultural data is provided by the Windows operating system.

  • 在所有版本的 Unix 平台上執行的.NET Core,文化特性的資料會提供Unicode (ICU) 程式庫的多語系元件In all versions of .NET Core running on Unix platforms, cultural data is provided by the International Components for Unicode (ICU) Library. ICU 程式庫的特定版本取決於個別的作業系統。The specific version of the ICU Library depends on the individual operating system.

因為這個緣故,在特定.NET 實作、 平台或版本,您可以使用的文化特性可能無法在不同.NET 實作、 平台或版本。Because of this, a culture available on a particular .NET implementation, platform, or version may not be available on a different .NET implementation, platform, or version.

某些CultureInfo物件基礎的平台而有所不同。Some CultureInfo objects differ depending on the underlying platform. 特別是,「 ZH-CN 」 或中文 (簡體,中國) 和 ZH-TW、 中文 (繁體,台灣),會在 Windows 系統上可用的文化特性,但會在 Unix 系統上的別名文化特性。In particular, "zh-CN", or Chinese (Simplified, China) and zh-TW, or Chinese (Traditional, Taiwan), are available cultures on Windows systems, but they are aliased cultures on Unix systems. 「 ZH-CN 」 是 「 Hans-ZH-CN"文化特性的別名和"ZH-TW"是"Hant-ZH-TW"文化特性的別名。"zh-CN" is an alias for the "zh-Hans-CN" culture, and "zh-TW" is an alias for the "zh-Hant-TW" culture. 別名的文化特性不會傳回呼叫GetCultures方法,可能有不同的屬性值,包括不同Parent文化特性,比與其 Windows 對應項目。Aliased cultures are not returned by calls to the GetCultures method and may have different property values, including different Parent cultures, than their Windows counterparts. 這些 differenes ZH-CN 和 ZH-TW 文化特性,包括下列:For the zh-CN and zh-TW cultures, these differenes include the following:

  • Windows 系統上 「 ZH-CN 」 文化特性的父文化特性 」 Zh-hans",而"ZH-TW"文化特性的父文化特性 」 Zh-hant"。On Windows systems, the parent culture of the "zh-CN" culture is "zh-Hans", and the parent culture of the "zh-TW" culture is "zh-Hant". 這些文化特性的父文化特性是 「 zh"。The parent culture of both these cultures is "zh". 在 Unix 系統上兩個文化特性的父代會是"zh 」。On Unix systems, the parents of both cultures are "zh". 這表示,如果您未提供特定文化特性資源之 「 ZH-CN"或"ZH-TW"文化特性,但不要提供資源的中性 」-Zh-hans 」 或 「 Zh-hant"文化特性,您的應用程式會載入在 Windows 上,但不是能在 Unix 中性文化特性的資源.This means that, if you don't provide culture-specific resources for the "zh-CN" or "zh-TW" cultures but do provide a resources for the neutral "zh-Hans" or "zh-Hant" culture, your application will load the resources for the neutral culture on Windows but not on Unix. Unix 系統上,您必須明確設定執行緒的CurrentUICulture"Zh-hans 」 或 「 Zh-hant"。On Unix systems, you must explicitly set the thread's CurrentUICulture to either "zh-Hans" or "zh-Hant".

  • 在 Windows 系統上,呼叫CultureInfo.Equals表示執行個體上的 「 ZH-CN 」 文化特性,並將其傳遞 「 Hans-ZH-CN"的執行個體傳回trueOn Windows systems, calling CultureInfo.Equals on an instance that represents the "zh-CN" culture and passing it a "zh-Hans-CN" instance returns true. 在 Unix 系統上的方法呼叫傳回falseOn Unix systems, the method call returns false. 此行為也適用於呼叫Equals上"ZH-TW"CultureInfo執行個體,並將其傳遞"Hant-Zh-tw"執行個體。This behavior also applies to calling Equals on a "zh-TW" CultureInfo instance and passing it a "zh-Hant-Tw" instance.

動態的文化特性的資料Dynamic culture data

除了文化特性而異,文化特性的資料是動態的。Except for the invariant culture, culture data is dynamic. 這是也適用於預先定義的文化特性。This is true even for the predefined cultures. 例如,國家或地區採用新的貨幣、 變更其拼字的文字,或變更其慣用的行事曆和文化特性定義變更來追蹤這。For example, countries or regions adopt new currencies, change their spellings of words, or change their preferred calendar, and culture definitions change to track this. 自訂文化特性可能會有所變更,恕不另行通知,並可能會由自訂取代的文化特性覆寫任何特定的文化特性。Custom cultures are subject to change without notice, and any specific culture might be overridden by a custom replacement culture. 此外下, 面所述,個別使用者可以覆寫文化特性喜好設定。Also, as discussed below, an individual user can override cultural preferences. 應用程式一律應在執行階段取得文化特性的資料。Applications should always obtain culture data at run time.

警告

儲存資料時,您的應用程式應該使用文化特性而異,一種二進位格式或特定文化特性無關的格式。When saving data, your application should use the invariant culture, a binary format, or a specific culture-independent format. 根據目前文化特性而異,以外特定文化特性相關聯的值已儲存的資料可能會變得無法讀取,或如果該文化特性變更,可能會變更的意義。Data saved according to the current values associated with a particular culture, other than the invariant culture, might become unreadable or might change in meaning if that culture changes.

目前 UI 文化特性與目前的文化特性The current culture and current UI culture

在.NET 應用程式中的每個執行緒有目前的文化特性和目前的 UI 文化特性。Every thread in a .NET application has a current culture and a current UI culture. 目前的文化特性會決定格式設定慣例的日期、 時間、 數字和貨幣值、 文字、 大小寫慣例和比較字串的方式的排序次序。The current culture determines the formatting conventions for dates, times, numbers, and currency values, the sort order of text, casing conventions, and the ways in which strings are compared. 目前的 UI 文化特性用來擷取在執行階段的特定文化特性的資源。The current UI culture is used to retrieve culture-specific resources at runtime.

注意

如需如何在個別執行緒上決定的目前和目前 UI 文化特性資訊,請參閱文化特性和執行緒一節。For information on how the current and current UI culture is determined on a per-thread basis, see the Culture and threads section. 如需目前與目前 UI 文化特性如何判斷在執行緒上執行新的應用程式定義域和執行緒跨越應用程式定義域界限,請參閱文化特性和應用程式定義域一節。For information on how the current and current UI culture is determined on threads executing in a new application domain, and on threads that cross application domain boundaries, see the Culture and application domains section. 如需如何判斷目前與目前執行工作為基礎的非同步作業的執行緒上的資訊,請參閱文化特性和以工作為基礎的非同步作業一節。For information on how the current and current is determined on threads performing task-based asynchronous operations, see the Culture and task-based asynchronous operations section.

如需詳細的目前文化特性的詳細資訊,請參閱CultureInfo.CurrentCulture屬性主題。For more detailed information on the current culture, see the CultureInfo.CurrentCulture property topic. 如需詳細的目前 UI 文化特性的詳細資訊,請參閱CultureInfo.CurrentUICulture屬性主題。For more detailed information on the current UI culture, see the CultureInfo.CurrentUICulture property topic.

擷取目前和目前 UI 文化特性Retrieving the current and current UI cultures

您可以取得CultureInfo物件,表示目前的文化特性,在兩種方式之一:You can get a CultureInfo object that represents the current culture in either of two ways:

下列範例會擷取這兩個屬性值,比較它們,以顯示它們相等,而會顯示目前的文化特性名稱。The following example retrieves both property values, compares them to show that they are equal, and displays the name of the current culture.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      CultureInfo culture1 = CultureInfo.CurrentCulture;
      CultureInfo culture2 = Thread.CurrentThread.CurrentCulture;
      Console.WriteLine("The current culture is {0}", culture1.Name);
      Console.WriteLine("The two CultureInfo objects are equal: {0}",
                        culture1 == culture2);
   }
}
// The example displays output like the following:
//     The current culture is en-US
//     The two CultureInfo objects are equal: True
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      Dim culture1 As CultureInfo = CultureInfo.CurrentCulture
      Dim culture2 As CultureInfo = Thread.CurrentThread.CurrentCulture
      Console.WriteLine("The current culture is {0}", culture1.Name)
      Console.WriteLine("The two CultureInfo objects are equal: {0}",
                        culture1.Equals(culture2))
   End Sub
End Module
' The example displays output like the following:
'     The current culture is en-US
'     The two CultureInfo objects are equal: True

您可以取得CultureInfo物件,代表目前 UI 文化特性,在兩種方式之一:You can get a CultureInfo object that represents the current UI culture in either of two ways:

下列範例會擷取這兩個屬性值,比較它們,以顯示它們相等,並顯示目前 UI 文化特性的名稱。The following example retrieves both property values, compares them to show that they are equal, and displays the name of the current UI culture.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      CultureInfo uiCulture1 = CultureInfo.CurrentUICulture;
      CultureInfo uiCulture2 = Thread.CurrentThread.CurrentUICulture;
      Console.WriteLine("The current UI culture is {0}", uiCulture1.Name);
      Console.WriteLine("The two CultureInfo objects are equal: {0}",
                        uiCulture1 == uiCulture2);
   }
}
// The example displays output like the following:
//     The current UI culture is en-US
//     The two CultureInfo objects are equal: True
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      Dim uiCulture1 As CultureInfo = CultureInfo.CurrentUICulture
      Dim uiCulture2 As CultureInfo = Thread.CurrentThread.CurrentUICulture
      Console.WriteLine("The current UI culture is {0}", uiCulture1.Name)
      Console.WriteLine("The two CultureInfo objects are equal: {0}",
                        uiCulture1.Equals(uiCulture2))
   End Sub
End Module
' The example displays output like the following:
'     The current UI culture is en-US
'     The two CultureInfo objects are equal: True

設定目前和目前 UI 文化特性Setting the current and current UI cultures

若要變更文化特性和 UI 文化特性的執行緒,執行下列作業:To change the culture and UI culture of a thread, do the following:

  1. 具現化CultureInfo物件,表示該文化特性,藉由呼叫CultureInfo類別建構函式,並將其傳遞文化特性名稱。Instantiate a CultureInfo object that represents that culture by calling a CultureInfo class constructor and passing it the name of the culture. CultureInfo(String)建構函式具現化CultureInfo反映使用者的物件會覆寫,如果新的文化特性與目前的 Windows 文化特性相同。The CultureInfo(String) constructor instantiates a CultureInfo object that reflects user overrides if the new culture is the same as the current Windows culture. CultureInfo(String, Boolean)建構函式可讓您指定是否新具現化CultureInfo物件會反映新的文化特性是否與目前的 Windows 文化特性相同,會覆寫使用者。The CultureInfo(String, Boolean) constructor allows you to specify whether the newly instantiated CultureInfo object reflects user overrides if the new culture is the same as the current Windows culture.

  2. 指派CultureInfo物件至CultureInfo.CurrentCultureCultureInfo.CurrentUICulture.NET Core 和.NET Framework 4.6 和更新版本上的屬性。Assign the CultureInfo object to the CultureInfo.CurrentCulture or CultureInfo.CurrentUICulture property on .NET Core and .NET Framework 4.6 and later versions. (.NET Framework 4.5.2 和舊版中,指派 youcCultureInfo物件至Thread.CurrentCultureThread.CurrentUICulture屬性。)(On .NET Framework 4.5.2 and earlier versions, youc an assign the CultureInfo object to the Thread.CurrentCulture or Thread.CurrentUICulture property.)

下列範例會擷取目前文化特性。The following example retrieves the current culture. 如果是法文 (法國) 文化特性以外的任何項目,它會將目前的文化特性變更為法文 (法國)。If it is anything other than the French (France) culture, it changes the current culture to French (France). 否則,它目前的文化特性變更為法文 (盧森堡)。Otherwise, it changes the current culture to French (Luxembourg).

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo current = CultureInfo.CurrentCulture;
      Console.WriteLine("The current culture is {0}", current.Name);
      CultureInfo newCulture;
      if (current.Name.Equals("fr-FR"))
         newCulture = new CultureInfo("fr-LU");
      else   
         newCulture = new CultureInfo("fr-FR");
      
      CultureInfo.CurrentCulture = newCulture;
      Console.WriteLine("The current culture is now {0}", 
                        CultureInfo.CurrentCulture.Name);   
   }
}
// The example displays output like the following:
//     The current culture is en-US
//     The current culture is now fr-FR
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim current As CultureInfo = CultureInfo.CurrentCulture
      Console.WriteLine("The current culture is {0}", current.Name)
      Dim newCulture As CultureInfo
      If current.Name.Equals("fr-FR") Then
         newCulture = New CultureInfo("fr-LU")
      Else   
         newCulture = new CultureInfo("fr-FR")
      End If
      
      CultureInfo.CurrentCulture = newCulture
      Console.WriteLine("The current culture is now {0}", 
                        CultureInfo.CurrentCulture.Name)   
   End Sub
End Module
' The example displays output like the following:
'     The current culture is en-US
'     The current culture is now fr-FR

下列範例會擷取目前文化特性。The following example retrieves the current culture. 如果是任何其他的斯洛維尼亞文 (斯洛維尼亞) 文化特性,它將目前的文化特性變更為斯洛維尼亞文 (斯洛維尼亞)。If it is anything other the Slovenian (Slovenia) culture, it changes the current culture to Slovenian (Slovenia). 否則,它會變更目前的文化特性設為克羅埃西亞文 (克羅埃西亞)。Otherwise, it changes the current culture to Croatian (Croatia).

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo current = CultureInfo.CurrentUICulture;
      Console.WriteLine("The current UI culture is {0}", current.Name);
      CultureInfo newUICulture;
      if (current.Name.Equals("sl-SI"))
         newUICulture = new CultureInfo("hr-HR");
      else   
         newUICulture = new CultureInfo("sl-SI");
      
      CultureInfo.CurrentUICulture = newUICulture;
      Console.WriteLine("The current UI culture is now {0}", 
                        CultureInfo.CurrentUICulture.Name);   
   }
}
// The example displays output like the following:
//     The current UI culture is en-US
//     The current UI culture is now sl-SI
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim current As CultureInfo = CultureInfo.CurrentUICulture
      Console.WriteLine("The current UI culture is {0}", current.Name)
      Dim newUICulture As CultureInfo
      If current.Name.Equals("sl-SI") Then
         newUICulture = New CultureInfo("hr-HR")
      Else   
         newUICulture = new CultureInfo("sl-SI")
      End If
      
      CultureInfo.CurrentUICulture = newUICulture
      Console.WriteLine("The current UI culture is now {0}", 
                        CultureInfo.CurrentUICulture.Name)   
   End Sub
End Module
' The example displays output like the following:
'     The current UI culture is en-US
'     The current UI culture is now sl-SI

取得所有文化特性Getting all cultures

您可以藉由呼叫擷取所有在本機電腦上使用的文化特性或文化特性的陣列特定類別GetCultures方法。You can retrieve an array specific categories of cultures or of all the cultures available on the local computer by calling the GetCultures method. 例如,您可以擷取自訂文化特性、 特定的文化特性或中性文化特性單獨或合併。For example, you can retrieve custom cultures, specific cultures, or neutral cultures either alone or in combination.

下列範例會呼叫GetCultures方法兩次,第一System.Globalization.CultureTypes列舉的成員,才能擷取所有的自訂文化特性和System.Globalization.CultureTypes来擷取所有取代的文化特性的列舉型別成員。The following example calls the GetCultures method twice, first with the System.Globalization.CultureTypes enumeration member to retrieve all custom cultures, and then with the System.Globalization.CultureTypes enumeration member to retrieve all replacement cultures.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // Get all custom cultures.
      CultureInfo[] custom = CultureInfo.GetCultures(CultureTypes.UserCustomCulture);
      if (custom.Length == 0) { 
         Console.WriteLine("There are no user-defined custom cultures.");
      }
      else {
         Console.WriteLine("Custom cultures:");
         foreach (var culture in custom) 
            Console.WriteLine("   {0} -- {1}", culture.Name, culture.DisplayName);    
      }
      Console.WriteLine();
      
      // Get all replacement cultures.
      CultureInfo[] replacements = CultureInfo.GetCultures(CultureTypes.ReplacementCultures);
      if (replacements.Length == 0) { 
         Console.WriteLine("There are no replacement cultures.");
      }                                             
      else {
         Console.WriteLine("Replacement cultures:");
         foreach (var culture in replacements) 
            Console.WriteLine("   {0} -- {1}", culture.Name, culture.DisplayName);    
      }
      Console.WriteLine();
   }
}
// The example displays output like the following:
//     Custom cultures:
//        x-en-US-sample -- English (United States)
//        fj-FJ -- Boumaa Fijian (Viti)
//     
//     There are no replacement cultures.
Imports System.Globalization

Module Example
   Public Sub Main()
      ' Get all custom cultures.
      Dim custom() As CultureInfo = CultureInfo.GetCultures(CultureTypes.UserCustomCulture)
      If custom.Length = 0 Then 
         Console.WriteLine("There are no user-defined custom cultures.")
      Else
         Console.WriteLine("Custom cultures:")
         For Each culture In custom 
            Console.WriteLine("   {0} -- {1}", culture.Name, culture.DisplayName)
         Next       
      End If
      Console.WriteLine()
      
      ' Get all replacement cultures.
      Dim replacements() As CultureInfo = CultureInfo.GetCultures(CultureTypes.ReplacementCultures)
      If replacements.Length = 0 Then 
         Console.WriteLine("There are no replacement cultures.")
      Else 
         Console.WriteLine("Replacement cultures:")
         For Each culture in replacements 
            Console.WriteLine("   {0} -- {1}", culture.Name, culture.DisplayName)    
         Next
      End If
      Console.WriteLine()
   End Sub
End Module
' The example displays output like the following:
'     Custom cultures:
'        x-en-US-sample -- English (United States)
'        fj-FJ -- Boumaa Fijian (Viti)
'     
'     There are no replacement cultures.

文化特性和執行緒Culture and threads

新的應用程式執行緒啟動時,其目前的文化特性和目前 UI 文化特性是會定義由目前的系統文化特性,而不是由目前執行緒文化特性。When a new application thread is started, its current culture and current UI culture are defined by the current system culture, and not by the current thread culture. 下列範例會說明其間的差異。The following example illustrates the difference. 它會設定應用程式執行緒的目前 UI 文化特性與目前的文化特性為法文 (法國) 文化特性 (FR-FR)。It sets the current culture and current UI culture of an application thread to the French (France) culture (fr-FR). 如果目前的文化特性已經為 FR-FR,則範例會將它設定為英文 (美國) 文化特性 (EN-US)。If the current culture is already fr-FR, the example sets it to the English (United States) culture (en-US). 它會顯示為貨幣值的三個隨機數字,並接著會建立新的執行緒,而接著會三個比較隨機的數字顯示為貨幣值。It displays three random numbers as currency values and then creates a new thread, which, in turn, displays three more random numbers as currency values. 但是,例所示的輸出,顯示新的執行緒的貨幣值不會反映法文 (法國) 文化特性格式化慣例,不同於主應用程式執行緒的輸出。But as the output from the example shows, the currency values displayed by the new thread do not reflect the formatting conventions of the French (France) culture, unlike the output from the main application thread.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   static Random rnd = new Random();
   
   public static void Main()
   {
      if (Thread.CurrentThread.CurrentCulture.Name != "fr-FR") {
         // If current culture is not fr-FR, set culture to fr-FR.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
         Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR");
      }
      else {
         // Set culture to en-US.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
         Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");
      }
      ThreadProc();
          
      Thread worker = new Thread(ThreadProc);
      worker.Name = "WorkerThread";
      worker.Start();
   }
   
   private static void DisplayThreadInfo()
   {
      Console.WriteLine("\nCurrent Thread Name: '{0}'", 
                        Thread.CurrentThread.Name);
      Console.WriteLine("Current Thread Culture/UI Culture: {0}/{1}", 
                        Thread.CurrentThread.CurrentCulture.Name,
                        Thread.CurrentThread.CurrentUICulture.Name);                        
   }
   
   private static void DisplayValues()
   {
      // Create new thread and display three random numbers.
      Console.WriteLine("Some currency values:");
      for (int ctr = 0; ctr <= 3; ctr++)
         Console.WriteLine("   {0:C2}", rnd.NextDouble() * 10);                        
   }
   
   private static void ThreadProc()
   {
      DisplayThreadInfo();
      DisplayValues();
   }
}
// The example displays output similar to the following:
//       Current Thread Name: ''
//       Current Thread Culture/UI Culture: fr-FR/fr-FR
//       Some currency values:
//          8,11 €
//          1,48 €
//          8,99 €
//          9,04 €
//       
//       Current Thread Name: 'WorkerThread'
//       Current Thread Culture/UI Culture: en-US/en-US
//       Some currency values:
//          $6.72
//          $6.35
//          $2.90
//          $7.72
Imports System.Globalization
Imports System.Threading

Module Example
   Dim rnd As New Random()
   
   Public Sub Main()
      If Thread.CurrentThread.CurrentCulture.Name <> "fr-FR" Then
         ' If current culture is not fr-FR, set culture to fr-FR.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR")
         Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR")
      Else
         ' Set culture to en-US.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
         Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US")
      End If
      ThreadProc()
          
       Dim worker As New Thread(AddressOf ThreadProc)
       worker.Name = "WorkerThread"
       worker.Start()
   End Sub
   
   Private Sub DisplayThreadInfo()
      Console.WriteLine()
      Console.WriteLine("Current Thread Name: '{0}'", 
                        Thread.CurrentThread.Name)
      Console.WriteLine("Current Thread Culture/UI Culture: {0}/{1}", 
                        Thread.CurrentThread.CurrentCulture.Name,
                        Thread.CurrentThread.CurrentUICulture.Name)                        
   End Sub
   
   Private Sub DisplayValues()
      ' Create new thread and display three random numbers.
      Console.WriteLine("Some currency values:")
      For ctr As Integer = 0 To 3
         Console.WriteLine("   {0:C2}", rnd.NextDouble() * 10)                        
      Next
   End Sub
   
   Private Sub ThreadProc()
      DisplayThreadInfo()
      DisplayValues()
   End Sub
End Module
' The example displays output similar to the following:
'       Current Thread Name: ''
'       Current Thread Culture/UI Culture: fr-FR/fr-FR
'       Some currency values:
'          8,11 €
'          1,48 €
'          8,99 €
'          9,04 €
'       
'       Current Thread Name: 'WorkerThread'
'       Current Thread Culture/UI Culture: en-US/en-US
'       Some currency values:
'          $6.72
'          $6.35
'          $2.90
'          $7.72

在之前的.NET Framework 的版本中.NET Framework 4.5.NET Framework 4.5,則確定主應用程式執行緒都與所有其他背景工作執行緒是共用相同的文化特性的常見方式是將整個應用程式的文化特性的名稱或CultureInfo物件表示整個應用程式的文化特性System.Threading.ParameterizedThreadStart委派。In versions of the .NET Framework before the .NET Framework 4.5.NET Framework 4.5, the most common way to ensure that the main application thread shares the same culture with all other worker threads is to pass either the name of the application-wide culture or a CultureInfo object that represents the application-wide culture to a System.Threading.ParameterizedThreadStart delegate. 下列範例會使用這種方法,以確保顯示兩個執行緒的貨幣值會反映相同的文化特性的格式化慣例。The following example uses this approach to ensure that the currency values displayed by two threads reflect the formatting conventions of the same culture.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   static Random rnd = new Random();
   
   public static void Main()
   {
      if (Thread.CurrentThread.CurrentCulture.Name != "fr-FR") {
         // If current culture is not fr-FR, set culture to fr-FR.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
         Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR");
      }   
      else {
         // Set culture to en-US.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
         Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");
      }
      DisplayThreadInfo();
      DisplayValues();
          
       Thread worker = new Thread(Example.ThreadProc);
       worker.Name = "WorkerThread";
       worker.Start(Thread.CurrentThread.CurrentCulture);
   }
   
   private static void DisplayThreadInfo()
   {
      Console.WriteLine("\nCurrent Thread Name: '{0}'", 
                        Thread.CurrentThread.Name);
      Console.WriteLine("Current Thread Culture/UI Culture: {0}/{1}", 
                        Thread.CurrentThread.CurrentCulture.Name,
                        Thread.CurrentThread.CurrentUICulture.Name);                        
   }
   
   private static void DisplayValues()
   {
      // Create new thread and display three random numbers.
      Console.WriteLine("Some currency values:");
      for (int ctr = 0; ctr <= 3; ctr++)
         Console.WriteLine("   {0:C2}", rnd.NextDouble() * 10);                        
   }
   
   private static void ThreadProc(Object obj) 
   {
      Thread.CurrentThread.CurrentCulture = (CultureInfo) obj;
      Thread.CurrentThread.CurrentUICulture = (CultureInfo) obj;
      DisplayThreadInfo();
      DisplayValues();
   }
}
// The example displays output similar to the following:
//       Current Thread Name: ''
//       Current Thread Culture/UI Culture: fr-FR/fr-FR
//       Some currency values:
//          6,83 €
//          3,47 €
//          6,07 €
//          1,70 €
//       
//       Current Thread Name: 'WorkerThread'
//       Current Thread Culture/UI Culture: fr-FR/fr-FR
//       Some currency values:
//          9,54 €
//          9,50 €
//          0,58 €
//          6,91 €
Imports System.Globalization
Imports System.Threading

Module Example
   Dim rnd As New Random()
   
   Public Sub Main()
      If Thread.CurrentThread.CurrentCulture.Name <> "fr-FR" Then
         ' If current culture is not fr-FR, set culture to fr-FR.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR")
         Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR")
      Else
         ' Set culture to en-US.
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
         Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US")
      End If
      DisplayThreadInfo()
      DisplayValues()
          
       Dim worker As New Thread(AddressOf ThreadProc)
       worker.Name = "WorkerThread"
       worker.Start(Thread.CurrentThread.CurrentCulture)
   End Sub
   
   Private Sub DisplayThreadInfo()
      Console.WriteLine()
      Console.WriteLine("Current Thread Name: '{0}'", 
                        Thread.CurrentThread.Name)
      Console.WriteLine("Current Thread Culture/UI Culture: {0}/{1}", 
                        Thread.CurrentThread.CurrentCulture.Name,
                        Thread.CurrentThread.CurrentUICulture.Name)                        
   End Sub
   
   Private Sub DisplayValues()
      ' Create new thread and display three random numbers.
      Console.WriteLine("Some currency values:")
      For ctr As Integer = 0 To 3
         Console.WriteLine("   {0:C2}", rnd.NextDouble() * 10)                        
      Next
   End Sub
   
   Private Sub ThreadProc(obj As Object)
      Thread.CurrentThread.CurrentCulture = CType(obj, CultureInfo)
      Thread.CurrentThread.CurrentUICulture = CType(obj, CultureInfo)
      DisplayThreadInfo()
      DisplayValues()
   End Sub
End Module
' The example displays output similar to the following:
'       Current Thread Name: ''
'       Current Thread Culture/UI Culture: fr-FR/fr-FR
'       Some currency values:
'          6,83 €
'          3,47 €
'          6,07 €
'          1,70 €
'       
'       Current Thread Name: 'WorkerThread'
'       Current Thread Culture/UI Culture: fr-FR/fr-FR
'       Some currency values:
'          9,54 €
'          9,50 €
'          0,58 €
'          6,91 €

您可以設定的文化特性和 UI 文化特性的執行緒集區執行緒中類似的方式呼叫ThreadPool.QueueUserWorkItem(WaitCallback, Object)方法。You can set the culture and UI culture of thread pool threads in a similar manner by calling the ThreadPool.QueueUserWorkItem(WaitCallback, Object) method.

開頭.NET Framework 4.5.NET Framework 4.5,您可以設定的文化特性和 UI 文化特性,所有執行緒的應用程式定義域中更直接指派CultureInfo物件,表示該文化特性DefaultThreadCurrentCultureDefaultThreadCurrentUICulture屬性。Starting with the .NET Framework 4.5.NET Framework 4.5, you can set the culture and UI culture of all threads in an application domain more directly by assigning a CultureInfo object that represents that culture to the DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties. 下列範例會使用這些屬性,以確保 預設應用程式定義域中的所有執行緒都共用相同的文化特性。The following example uses these properties to ensure that all threads in the default application domain share the same culture.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   static Random rnd = new Random();
   
   public static void Main()
   {
      if (Thread.CurrentThread.CurrentCulture.Name != "fr-FR") {
         // If current culture is not fr-FR, set culture to fr-FR.
         CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
         CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR");
      }   
      else {
         // Set culture to en-US.
         CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
         CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");
      }
      ThreadProc();
          
      Thread worker = new Thread(Example.ThreadProc);
      worker.Name = "WorkerThread";
      worker.Start();
   }
   
   private static void DisplayThreadInfo()
   {
      Console.WriteLine("\nCurrent Thread Name: '{0}'", 
                        Thread.CurrentThread.Name);
      Console.WriteLine("Current Thread Culture/UI Culture: {0}/{1}", 
                        Thread.CurrentThread.CurrentCulture.Name,
                        Thread.CurrentThread.CurrentUICulture.Name);                        
   }
   
   private static void DisplayValues()
   {
      // Create new thread and display three random numbers.
      Console.WriteLine("Some currency values:");
      for (int ctr = 0; ctr <= 3; ctr++)
         Console.WriteLine("   {0:C2}", rnd.NextDouble() * 10);                        
   }
   
   private static void ThreadProc() 
   {
      DisplayThreadInfo();
      DisplayValues();
   }
}
// The example displays output similar to the following:
//       Current Thread Name: ''
//       Current Thread Culture/UI Culture: fr-FR/fr-FR
//       Some currency values:
//          6,83 €
//          3,47 €
//          6,07 €
//          1,70 €
//       
//       Current Thread Name: 'WorkerThread'
//       Current Thread Culture/UI Culture: fr-FR/fr-FR
//       Some currency values:
//          9,54 €
//          9,50 €
//          0,58 €
//          6,91 €
Imports System.Globalization
Imports System.Threading

Module Example
   Dim rnd As New Random()
   
   Public Sub Main()
      If Thread.CurrentThread.CurrentCulture.Name <> "fr-FR" Then
         ' If current culture is not fr-FR, set culture to fr-FR.
         CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR")
         CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR")
      Else
         ' Set culture to en-US.
         CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
         CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture("en-US")
      End If
      ThreadProc()

       Dim worker As New Thread(AddressOf ThreadProc)
       worker.Name = "WorkerThread"
       worker.Start()
   End Sub
   
   Private Sub DisplayThreadInfo()
      Console.WriteLine()
      Console.WriteLine("Current Thread Name: '{0}'", 
                        Thread.CurrentThread.Name)
      Console.WriteLine("Current Thread Culture/UI Culture: {0}/{1}", 
                        Thread.CurrentThread.CurrentCulture.Name,
                        Thread.CurrentThread.CurrentUICulture.Name)                        
   End Sub
   
   Private Sub DisplayValues()
      ' Create new thread and display three random numbers.
      Console.WriteLine("Some currency values:")
      For ctr As Integer = 0 To 3
         Console.WriteLine("   {0:C2}", rnd.NextDouble() * 10)                        
      Next
   End Sub
   
   Private Sub ThreadProc()
      DisplayThreadInfo()
      DisplayValues()
   End Sub
End Module
' The example displays output similar to the following:
'       Current Thread Name: ''
'       Current Thread Culture/UI Culture: fr-FR/fr-FR
'       Some currency values:
'          6,83 €
'          3,47 €
'          6,07 €
'          1,70 €
'       
'       Current Thread Name: 'WorkerThread'
'       Current Thread Culture/UI Culture: fr-FR/fr-FR
'       Some currency values:
'          9,54 €
'          9,50 €
'          0,58 €
'          6,91 €

警告

雖然DefaultThreadCurrentCultureDefaultThreadCurrentUICulture屬性是靜態成員,它們會定義預設文化特性和只針對目前在設定這些屬性的值時間的應用程式定義域的預設 UI 文化特性。Although the DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties are static members, they define the default culture and default UI culture only for the application domain that is current at the time these property values are set. 如需詳細資訊,請參閱下一步 區段中,文化特性和應用程式定義域For more information, see the next section, Culture and application domains.

當您將值指派給DefaultThreadCurrentCultureDefaultThreadCurrentUICulture屬性、 文化特性和 UI 文化特性的應用程式定義域中的執行緒也變更如果他們未明確指派文化特性。When you assign values to the DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties, the culture and UI culture of the threads in the application domain also change if they have not explicitly been assigned a culture. 不過,這些執行緒反映新的文化特性設定,只有當目前的應用程式定義域中執行時。However, these threads reflect the new culture settings only while they execute in the current application domain. 如果這些執行緒會執行另一個應用程式定義域中,其文化特性會變成該應用程式定義域所定義的預設文化特性。If these threads execute in another application domain, their culture becomes the default culture defined for that application domain. 如此一來,我們建議您一定會設定主應用程式執行緒的文化特性,而不依賴DefaultThreadCurrentCultureDefaultThreadCurrentUICulture屬性來變更它。As a result, we recommend that you always set the culture of the main application thread, and not rely on the DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties to change it.

文化特性和應用程式網域Culture and application domains

DefaultThreadCurrentCultureDefaultThreadCurrentUICulture會明確地定義只會針對應用程式定義域的目前設定或擷取屬性值時的預設文化特性的靜態屬性。DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture are static properties that explicitly define a default culture only for the application domain that is current when the property value is set or retrieved. 下列範例預設應用程式定義域中的預設文化特性和預設 UI 文化特性設定為法文 (法國),然後使用AppDomainSetup類別和AppDomainInitializer委派以設定至新的應用程式定義域中的預設文化特性和 UI 文化特性俄文 (俄羅斯)。The following example sets the default culture and default UI culture in the default application domain to French (France), and then uses the AppDomainSetup class and the AppDomainInitializer delegate to set the default culture and UI culture in a new application domain to Russian (Russia). 然後,單一執行緒會每個應用程式定義域中執行兩種方法。A single thread then executes two methods in each application domain. 請注意,執行緒的文化特性和 UI 文化特性未明確設定;它們被衍生自的預設文化特性和 UI 文化特性的執行緒正在執行的應用程式定義域。Note that the thread's culture and UI culture are not explicitly set; they are derived from the default culture and UI culture of the application domain in which the thread is executing. 另請注意DefaultThreadCurrentCultureDefaultThreadCurrentUICulture屬性會傳回預設值CultureInfo是方法呼叫時,將最新的應用程式定義域的值。Note also that the DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties return the default CultureInfo values of the application domain that is current when the method call is made.

using System;
using System.Globalization;
using System.Reflection;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Set the default culture and display the current date in the current application domain.
      Info info1 = new Info();
      SetAppDomainCultures("fr-FR");
      
      // Create a second application domain.
      AppDomainSetup setup = new AppDomainSetup();
      setup.AppDomainInitializer = SetAppDomainCultures;
      setup.AppDomainInitializerArguments = new string[] { "ru-RU" };
      AppDomain domain = AppDomain.CreateDomain("Domain2", null, setup);
      // Create an Info object in the new application domain.
      Info info2 = (Info) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, 
                                                         "Info"); 

      // Execute methods in the two application domains.
      info2.DisplayDate();
      info2.DisplayCultures();
      
      info1.DisplayDate();
      info1.DisplayCultures();            
   }

   public static void SetAppDomainCultures(string[] names)
   {
      SetAppDomainCultures(names[0]);
   }
   
   public static void SetAppDomainCultures(string name)
   {
       try {
         CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture(name);
         CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture(name);
      }
      // If an exception occurs, we'll just fall back to the system default.
      catch (CultureNotFoundException) {
         return;
      }   
      catch (ArgumentException) {
         return;
      } 
   }
}

public class Info : MarshalByRefObject
{
   public void DisplayDate()
   {
      Console.WriteLine("Today is {0:D}", DateTime.Now);
   }
   
   public void DisplayCultures()
   {
      Console.WriteLine("Application domain is {0}", AppDomain.CurrentDomain.Id);
      Console.WriteLine("Default Culture: {0}", CultureInfo.DefaultThreadCurrentCulture);
      Console.WriteLine("Default UI Culture: {0}", CultureInfo.DefaultThreadCurrentUICulture);
   }
}
// The example displays the following output:
//       Today is 14 октября 2011 г.
//       Application domain is 2
//       Default Culture: ru-RU
//       Default UI Culture: ru-RU
//       Today is vendredi 14 octobre 2011
//       Application domain is 1
//       Default Culture: fr-FR
//       Default UI Culture: fr-FR
Imports System.Globalization
Imports System.Reflection
Imports System.Threading

Module Example
   Public Sub Main()
      ' Set the default culture and display the current date in the current application domain.
      Dim info1 As New Info()
      SetAppDomainCultures("fr-FR")
      
      ' Create a second application domain.
      Dim setup As New AppDomainSetup()
      setup.AppDomainInitializer = AddressOf SetAppDomainCultures
      setup.AppDomainInitializerArguments = { "ru-RU" }
      Dim domain As AppDomain = AppDomain.CreateDomain("Domain2", Nothing, setup)
      ' Create an Info object in the new application domain.
      Dim info2 As Info = CType(domain.CreateInstanceAndUnwrap(GetType(Example).Assembly.FullName, 
                                                               "Info"), Info) 

      ' Execute methods in the two application domains.
      info2.DisplayDate()
      info2.DisplayCultures()
      
      info1.DisplayDate()
      info1.DisplayCultures()            
   End Sub
   
   Public Sub SetAppDomainCultures(names() As String)
      SetAppDomainCultures(names(0))
   End Sub
   
   Public Sub SetAppDomainCultures(name As String)
       Try
         CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture(name)
         CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture(name)
      ' If an exception occurs, we'll just fall back to the system default.
      Catch e As CultureNotFoundException
         Return
      Catch e As ArgumentException
         Return
      End Try      
   End Sub
End Module

Public Class Info : Inherits MarshalByRefObject
   Public Sub DisplayDate()
      Console.WriteLine("Today is {0:D}", Date.Now)
   End Sub
   
   Public Sub DisplayCultures()
      Console.WriteLine("Application domain is {0}", AppDomain.CurrentDomain.Id)
      Console.WriteLine("Default Culture: {0}", CultureInfo.DefaultThreadCurrentCulture)
      Console.WriteLine("Default UI Culture: {0}", CultureInfo.DefaultThreadCurrentUICulture)
   End Sub
End Class
' The example displays the following output:
'       Today is 14 октября 2011 г.
'       Application domain is 2
'       Default Culture: ru-RU
'       Default UI Culture: ru-RU
'       Today is vendredi 14 octobre 2011
'       Application domain is 1
'       Default Culture: fr-FR
'       Default UI Culture: fr-FR

如需文化特性和應用程式定義域的詳細資訊,請參閱中的 「 應用程式定義域和執行緒 」 一節應用程式定義域主題。For more information about cultures and application domains, see the "Application Domains and Threads" section in the Application Domains topic.

文化特性和以工作為基礎的非同步作業Culture and task-based asynchronous operations

工作式非同步程式設計模式會使用TaskTask<TResult>物件以非同步方式執行委派,在執行緒集區的執行緒。The task-based asynchronous programming pattern uses Task and Task<TResult> objects to asynchronously execute delegates on thread pool threads. 特定工作執行所在的特定執行緒事先不知道,但只有在執行階段決定。The specific thread on which a particular task runs is not known in advance, but is determined only at runtime.

目標應用程式,.NET Framework 4.6.NET Framework 4.6或更新版本、 文化特性是非同步的作業內容的一部分。For apps that target the .NET Framework 4.6.NET Framework 4.6 or later versions, culture is part of an asynchronous operation's context. 換句話說,從應用程式為目標.NET Framework 4.6.NET Framework 4.6,預設的非同步作業繼承的值CurrentCultureCurrentUICulture從中啟動之執行緒的內容。In other words, starting with apps that target the .NET Framework 4.6.NET Framework 4.6, asynchronous operations by default inherit the values of the CurrentCulture and CurrentUICulture properties of the thread from which they are launched. 如果目前的文化特性或目前 UI 文化特性和不同系統的文化特性,目前的文化特性跨越執行緒界限,並會變成 正在執行非同步作業的執行緒集區執行緒的目前文化特性。If the current culture or current UI culture differs from the system culture, the current culture crosses thread boundaries and becomes the current culture of the thread pool thread that is executing an asynchronous operation.

下列範例提供一個簡單的範例。The following example provides a simple illustration. 它會使用TargetFrameworkAttribute屬性,以目標.NET Framework 4.6.NET Framework 4.6It uses the TargetFrameworkAttribute attribute to target the .NET Framework 4.6.NET Framework 4.6. 此範例會定義Func<TResult>委派, formatDelegate,傳回格式化為貨幣值的數字。The example defines a Func<TResult> delegate, formatDelegate, that returns some numbers formatted as currency values. 此範例將目前的系統文化特性變更為 「 法文 (法國) 或法文 (法國) 」 已經是目前的文化特性,英文 (美國)。The example changes the current system culture to either French (France) or, if French (France) is already the current culture, English (United States). 它然後:It then:

  • 使其在主應用程式的執行緒上執行以同步方式,直接叫用委派。Invokes the delegate directly so that it runs synchronously on the main app thread.

  • 建立執行緒集區執行緒以非同步方式執行委派的工作。Creates a task that executes the delegate asynchronously on a thread pool thread.

  • 建立工作,藉由呼叫委派以同步方式執行的主要應用程式執行緒上Task.RunSynchronously方法。Creates a task that executes the delegate synchronously on the main app thread by calling the Task.RunSynchronously method.

如範例輸出所示,當目前的文化特性會變更為法文 (法國),目前的工作會叫用非同步執行緒文化特性會變成該非同步作業的目前文化特性。As the output from the example shows, when the current culture is changed to French (France), the current culture of the thread from which tasks are invoked asynchronously becomes the current culture for that asynchronous operation.

using System;
using System.Globalization;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;

[assembly:TargetFramework(".NETFramework,Version=v4.6")]

public class Example
{
   
   public static void Main()
   {
       decimal[] values = { 163025412.32m, 18905365.59m };
       string formatString = "C2";
       Func<String> formatDelegate = () => { string output = String.Format("Formatting using the {0} culture on thread {1}.\n",
                                                                           CultureInfo.CurrentCulture.Name,
                                                                           Thread.CurrentThread.ManagedThreadId);
                                             foreach (var value in values)
                                                output += String.Format("{0}   ", value.ToString(formatString));
                                                   
                                             output += Environment.NewLine;
                                             return output;
                                           };
       
       Console.WriteLine("The example is running on thread {0}", 
                         Thread.CurrentThread.ManagedThreadId);
       // Make the current culture different from the system culture.
       Console.WriteLine("The current culture is {0}", 
                         CultureInfo.CurrentCulture.Name);
       if (CultureInfo.CurrentCulture.Name == "fr-FR")
          Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
       else
          Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

       Console.WriteLine("Changed the current culture to {0}.\n",
                         CultureInfo.CurrentCulture.Name);
       
       // Execute the delegate synchronously.
       Console.WriteLine("Executing the delegate synchronously:");
       Console.WriteLine(formatDelegate());
       
       // Call an async delegate to format the values using one format string.
       Console.WriteLine("Executing a task asynchronously:"); 
       var t1 = Task.Run(formatDelegate);
       Console.WriteLine(t1.Result);
       
       Console.WriteLine("Executing a task synchronously:");
       var t2 = new Task<String>(formatDelegate); 
       t2.RunSynchronously();
       Console.WriteLine(t2.Result);
   }
}
// The example displays the following output:
//         The example is running on thread 1
//         The current culture is en-US
//         Changed the current culture to fr-FR.
//
//         Executing the delegate synchronously:
//         Formatting using the fr-FR culture on thread 1.
//         163 025 412,32 €   18 905 365,59 €
//
//         Executing a task asynchronously:
//         Formatting using the fr-FR culture on thread 3.
//         163 025 412,32 €   18 905 365,59 €
//
//         Executing a task synchronously:
//         Formatting using the fr-FR culture on thread 1.
//         163 025 412,32 €   18 905 365,59 €
Imports System.Globalization
Imports System.Runtime.Versioning
Imports System.Threading
Imports System.Threading.Tasks

<Assembly:TargetFramework(".NETFramework,Version=v4.6")>

Module Example
   Public Sub Main()
       Dim values() As Decimal = { 163025412.32d, 18905365.59d }
       Dim formatString As String = "C2"
       Dim formatDelegate As Func(Of String) = Function()
                                                  Dim output As String = String.Format("Formatting using the {0} culture on thread {1}.",
                                                                                       CultureInfo.CurrentCulture.Name,
                                                                                       Thread.CurrentThread.ManagedThreadId)
                                                  output += Environment.NewLine
                                                  For Each value In values
                                                     output += String.Format("{0}   ", value.ToString(formatString))
                                                  Next 
                                                  output += Environment.NewLine
                                                  Return output
                                               End Function
       
       Console.WriteLine("The example is running on thread {0}", 
                         Thread.CurrentThread.ManagedThreadId)
       ' Make the current culture different from the system culture.
       Console.WriteLine("The current culture is {0}", 
                         CultureInfo.CurrentCulture.Name)
       If CultureInfo.CurrentCulture.Name = "fr-FR" Then
          Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US")
       Else
          Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR")
       End If
       Console.WriteLine("Changed the current culture to {0}.",
                         CultureInfo.CurrentCulture.Name)
       Console.WriteLine()                  
       
       ' Execute the delegate synchronously.
       Console.WriteLine("Executing the delegate synchronously:")
       Console.WriteLine(formatDelegate())
       
       ' Call an async delegate to format the values using one format string.
       Console.WriteLine("Executing a task asynchronously:") 
       Dim t1 = Task.Run(formatDelegate)
       Console.WriteLine(t1.Result)
       
       Console.WriteLine("Executing a task synchronously:")
       Dim t2 = New Task(Of String)(formatDelegate) 
       t2.RunSynchronously()
       Console.WriteLine(t2.Result)
   End Sub
End Module
' The example displays the following output:
'          The example is running on thread 1
'          The current culture is en-US
'          Changed the current culture to fr-FR.
'
'          Executing the delegate synchronously:
'          Formatting Imports the fr-FR culture on thread 1.
'          163 025 412,32 €   18 905 365,59 €
'
'          Executing a task asynchronously:
'          Formatting Imports the fr-FR culture on thread 3.
'          163 025 412,32 €   18 905 365,59 €
'
'          Executing a task synchronously:
'          Formatting Imports the fr-FR culture on thread 1.
'          163 025 412,32 €   18 905 365,59 €

之前的.NET Framework 版本為目標的應用程式的.NET Framework 4.6.NET Framework 4.6,或針對執行特定版本的.NET Framework 為目標的應用程式,呼叫執行緒的文化特性不是工作的內容的一部分。For apps that target versions of the .NET Framework prior to the .NET Framework 4.6.NET Framework 4.6, or for apps that do not target a particular version of the .NET Framework, the culture of the calling thread is not part of a task's context. 相反地,除非有明確定義,預設的新執行緒的文化特性就是系統的文化特性。Instead, unless one is explicitly defined, the culture of new threads by default is the system culture. 下列範例中,也就是與前一個範例相同,不同之處在於它缺乏TargetFrameworkAttribute屬性,可說明這點。The following example, which is identical to the previous example except that it lacks the TargetFrameworkAttribute attribute, illustrates this. 因為此範例執行所在系統的系統文化特性是工作的英文 (美國),可在執行緒集區執行緒上以非同步方式執行的文化特性是工作的 EN-US,而不是工作的 fr-fr。Because the system culture of the system on which the example executed was English (United States), the culture of the task that executes asynchronously on a thread pool thread is en-US rather than fr-FR.

using System;
using System.Globalization;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
       decimal[] values = { 163025412.32m, 18905365.59m };
       string formatString = "C2";
       Func<String> formatDelegate = () => { string output = String.Format("Formatting using the {0} culture on thread {1}.\n",
                                                                           CultureInfo.CurrentCulture.Name,
                                                                           Thread.CurrentThread.ManagedThreadId);
                                             foreach (var value in values)
                                                output += String.Format("{0}   ", value.ToString(formatString));
                                                   
                                             output += Environment.NewLine;
                                             return output;
                                           };
       
       Console.WriteLine("The example is running on thread {0}", 
                         Thread.CurrentThread.ManagedThreadId);
       // Make the current culture different from the system culture.
       Console.WriteLine("The current culture is {0}", 
                         CultureInfo.CurrentCulture.Name);
       if (CultureInfo.CurrentCulture.Name == "fr-FR")
          Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
       else
          Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

       Console.WriteLine("Changed the current culture to {0}.\n",
                         CultureInfo.CurrentCulture.Name);
       
       // Execute the delegate synchronously.
       Console.WriteLine("Executing the delegate synchronously:");
       Console.WriteLine(formatDelegate());
       
       // Call an async delegate to format the values using one format string.
       Console.WriteLine("Executing a task asynchronously:"); 
       var t1 = Task.Run(formatDelegate);
       Console.WriteLine(t1.Result);
       
       Console.WriteLine("Executing a task synchronously:");
       var t2 = new Task<String>(formatDelegate); 
       t2.RunSynchronously();
       Console.WriteLine(t2.Result);
   }
}
// The example displays the following output:
//     The example is running on thread 1
//     The current culture is en-US
//     Changed the current culture to fr-FR.
//     
//     Executing the delegate synchronously:
//     Formatting using the fr-FR culture on thread 1.
//     163 025 412,32 €   18 905 365,59 €
//     
//     Executing a task asynchronously:
//     Formatting using the en-US culture on thread 3.
//     $163,025,412.32   $18,905,365.59
//     
//     Executing a task synchronously:
//     Formatting using the fr-FR culture on thread 1.
//     163 025 412,32 €   18 905 365,59 €
Imports System.Globalization
Imports System.Runtime.Versioning
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
       Dim values() As Decimal = { 163025412.32d, 18905365.59d }
       Dim formatString As String = "C2"
       Dim formatDelegate As Func(Of String) = Function()
                                                  Dim output As String = String.Format("Formatting using the {0} culture on thread {1}.",
                                                                                       CultureInfo.CurrentCulture.Name,
                                                                                       Thread.CurrentThread.ManagedThreadId)
                                                  output += Environment.NewLine
                                                  For Each value In values
                                                     output += String.Format("{0}   ", value.ToString(formatString))
                                                  Next 
                                                  output += Environment.NewLine
                                                  Return output
                                               End Function
       
       Console.WriteLine("The example is running on thread {0}", 
                         Thread.CurrentThread.ManagedThreadId)
       ' Make the current culture different from the system culture.
       Console.WriteLine("The current culture is {0}", 
                         CultureInfo.CurrentCulture.Name)
       If CultureInfo.CurrentCulture.Name = "fr-FR" Then
          Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US")
       Else
          Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR")
       End If
       Console.WriteLine("Changed the current culture to {0}.",
                         CultureInfo.CurrentCulture.Name)
       Console.WriteLine()                  
       
       ' Execute the delegate synchronously.
       Console.WriteLine("Executing the delegate synchronously:")
       Console.WriteLine(formatDelegate())
       
       ' Call an async delegate to format the values using one format string.
       Console.WriteLine("Executing a task asynchronously:") 
       Dim t1 = Task.Run(formatDelegate)
       Console.WriteLine(t1.Result)
       
       Console.WriteLine("Executing a task synchronously:")
       Dim t2 = New Task(Of String)(formatDelegate) 
       t2.RunSynchronously()
       Console.WriteLine(t2.Result)
   End Sub
End Module
' The example displays the following output:
'     The example is running on thread 1
'     The current culture is en-US
'     Changed the current culture to fr-FR.
'     
'     Executing the delegate synchronously:
'     Formatting using the fr-FR culture on thread 1.
'     163 025 412,32 €   18 905 365,59 €
'     
'     Executing a task asynchronously:
'     Formatting using the en-US culture on thread 3.
'     $163,025,412.32   $18,905,365.59
'     
'     Executing a task synchronously:
'     Formatting using the fr-FR culture on thread 1.
'     163 025 412,32 €   18 905 365,59 €

從.NET Framework 版本為目標的應用程式.NET Framework 4.5.NET Framework 4.5和更新版本,但之前.NET Framework 4.6.NET Framework 4.6,您可以使用DefaultThreadCurrentCultureDefaultThreadCurrentUICulture屬性,以確保呼叫執行緒的文化特性會用於非同步工作在執行緒集區執行緒上執行。For apps that target versions of the .NET Framework from the .NET Framework 4.5.NET Framework 4.5 and later but prior to the .NET Framework 4.6.NET Framework 4.6, you can use the DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties to ensure that the culture of the calling thread is used in asynchronous tasks that execute on thread pool threads. 下列範例等同於上述範例中,不同之處在於它會使用DefaultThreadCurrentCulture屬性,以確認該執行緒集區執行緒有相同的文化特性,與主要應用程式的執行緒。The following example is identical to the previous example, except that it uses the DefaultThreadCurrentCulture property to ensure that thread pool threads have the same culture as the main app thread.

using System;
using System.Globalization;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
       decimal[] values = { 163025412.32m, 18905365.59m };
       string formatString = "C2";
       Func<String> formatDelegate = () => { string output = String.Format("Formatting using the {0} culture on thread {1}.\n",
                                                                           CultureInfo.CurrentCulture.Name,
                                                                           Thread.CurrentThread.ManagedThreadId);
                                             foreach (var value in values)
                                                output += String.Format("{0}   ", value.ToString(formatString));
                                                   
                                             output += Environment.NewLine;
                                             return output;
                                           };
       
       Console.WriteLine("The example is running on thread {0}", 
                         Thread.CurrentThread.ManagedThreadId);
       // Make the current culture different from the system culture.
       Console.WriteLine("The current culture is {0}", 
                         CultureInfo.CurrentCulture.Name);
       if (CultureInfo.CurrentCulture.Name == "fr-FR")
          Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
       else
          Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

       Console.WriteLine("Changed the current culture to {0}.\n",
                         CultureInfo.CurrentCulture.Name);
       CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CurrentCulture;
       
       // Execute the delegate synchronously.
       Console.WriteLine("Executing the delegate synchronously:");
       Console.WriteLine(formatDelegate());
       
       // Call an async delegate to format the values using one format string.
       Console.WriteLine("Executing a task asynchronously:"); 
       var t1 = Task.Run(formatDelegate);
       Console.WriteLine(t1.Result);
       
       Console.WriteLine("Executing a task synchronously:");
       var t2 = new Task<String>(formatDelegate); 
       t2.RunSynchronously();
       Console.WriteLine(t2.Result);
   }
}
// The example displays the following output:
//     The example is running on thread 1
//     The current culture is en-US
//     Changed the current culture to fr-FR.
//     
//     Executing the delegate synchronously:
//     Formatting using the fr-FR culture on thread 1.
//     163 025 412,32 €   18 905 365,59 €
//     
//     Executing a task asynchronously:
//     Formatting using the fr-FR culture on thread 3.
//     163 025 412,32 €   18 905 365,59 €
//     
//     Executing a task synchronously:
//     Formatting using the fr-FR culture on thread 1.
//     163 025 412,32 €   18 905 365,59 €
Imports System.Globalization
Imports System.Runtime.Versioning
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
       Dim values() As Decimal = { 163025412.32d, 18905365.59d }
       Dim formatString As String = "C2"
       Dim formatDelegate As Func(Of String) = Function()
                                                  Dim output As String = String.Format("Formatting using the {0} culture on thread {1}.",
                                                                                       CultureInfo.CurrentCulture.Name,
                                                                                       Thread.CurrentThread.ManagedThreadId)
                                                  output += Environment.NewLine
                                                  For Each value In values
                                                     output += String.Format("{0}   ", value.ToString(formatString))
                                                  Next 
                                                  output += Environment.NewLine
                                                  Return output
                                               End Function
       
       Console.WriteLine("The example is running on thread {0}", 
                         Thread.CurrentThread.ManagedThreadId)
       ' Make the current culture different from the system culture.
       Console.WriteLine("The current culture is {0}", 
                         CultureInfo.CurrentCulture.Name)
       If CultureInfo.CurrentCulture.Name = "fr-FR" Then
          Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US")
       Else
          Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR")
       End If
       Console.WriteLine("Changed the current culture to {0}.",
                         CultureInfo.CurrentCulture.Name)
       CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CurrentCulture
       Console.WriteLine()                  
       
       ' Execute the delegate synchronously.
       Console.WriteLine("Executing the delegate synchronously:")
       Console.WriteLine(formatDelegate())
       
       ' Call an async delegate to format the values using one format string.
       Console.WriteLine("Executing a task asynchronously:") 
       Dim t1 = Task.Run(formatDelegate)
       Console.WriteLine(t1.Result)
       
       Console.WriteLine("Executing a task synchronously:")
       Dim t2 = New Task(Of String)(formatDelegate) 
       t2.RunSynchronously()
       Console.WriteLine(t2.Result)
   End Sub
End Module
' The example displays the following output:
'       The example is running on thread 1
'       The current culture is en-US
'       Changed the current culture to fr-FR.
'       
'       Executing the delegate synchronously:
'       Formatting using the fr-FR culture on thread 1.
'       163 025 412,32 €   18 905 365,59 €
'       
'       Executing a task asynchronously:
'       Formatting using the fr-FR culture on thread 3.
'       163 025 412,32 €   18 905 365,59 €
'       
'       Executing a task synchronously:
'       Formatting using the fr-FR culture on thread 1.
'       163 025 412,32 €   18 905 365,59 €

DefaultThreadCurrentCultureDefaultThreadCurrentUICulture是每個應用程式定義域屬性; 也就是其所建立的預設文化特性的所有執行緒未明確都指派文化特性特定的應用程式定義域中。DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture are per-app domain properties; that is, they establish a default culture for all threads not explicitly assigned a culture in a specific application domain. 不過,對於目標的應用程式.NET Framework 4.6.NET Framework 4.6或更新版本中,會呼叫執行緒的文化特性仍非同步工作的內容的一部分,即使工作跨越應用程式定義域界限。However, for apps that target the .NET Framework 4.6.NET Framework 4.6 or later, the culture of the calling thread remains part of an asynchronous task's context even if the task crosses app domain boundaries.

下列範例示範即使在執行工作的方法可跨越應用程式定義域界限的呼叫執行緒文化特性,仍會以工作為基礎的非同步作業的目前文化特性。The following example shows that the calling thread's culture remains the current culture of a task-based asynchronous operation even if the method that the task is executing crosses application domain boundaries. 它會定義一個類別, DataRetriever,具有單一方法, GetFormattedNumber,介於 1 到 1,000 格式化為貨幣值,傳回的隨機的雙精確度浮點數。It defines a class, DataRetriever, with a single method, GetFormattedNumber, that returns a random double-precision floating-point number between 1 and 1,000 formatted as a currency value. 第一項工作會執行,只會具現化DataRetriever執行個體並呼叫其GetFormattedNumber方法。A first task is run that simply instantiates a DataRetriever instance and calls its GetFormattedNumber method. 第二個工作會報告其目前的應用程式定義域、 建立新的應用程式定義域、 具現化DataRetriever執行個體,在新的應用程式定義域,然後呼叫其GetFormattedNumber方法。A second task reports its current application domain, creates a new application domain, instantiates a DataRetriever instance in the new application domain, and calls its GetFormattedNumber method. 如範例輸出所示,目前的文化特性一直呼叫的執行緒,第一項工作和第二個工作都在相同的主應用程式定義域和第二個應用程式定義域中執行時。As the output from the example shows, the current culture has remained the same in the calling thread, the first task, and the second task both when it was executing in the main application domain and the second application domain.

using System;
using System.Globalization;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;

[assembly:TargetFramework(".NETFramework,Version=v4.6")]

public class Example
{
   public static void Main()
   {
       string formatString = "C2";
       Console.WriteLine("The example is running on thread {0}", 
                         Thread.CurrentThread.ManagedThreadId);
       // Make the current culture different from the system culture.
       Console.WriteLine("The current culture is {0}", 
                         CultureInfo.CurrentCulture.Name);
       if (CultureInfo.CurrentCulture.Name == "fr-FR")
          Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
       else
          Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

       Console.WriteLine("Changed the current culture to {0}.\n",
                         CultureInfo.CurrentCulture.Name);
       
       // Call an async delegate to format the values using one format string.
       Console.WriteLine("Executing a task asynchronously in the main appdomain:"); 
       var t1 = Task.Run(() => { DataRetriever d = new DataRetriever();
                                 return d.GetFormattedNumber(formatString);
                               });
       Console.WriteLine(t1.Result);
       Console.WriteLine(); 
       
       Console.WriteLine("Executing a task synchronously in two appdomains:");
       var t2 = Task.Run(() => { Console.WriteLine("Thread {0} is running in app domain '{1}'", 
                                                   Thread.CurrentThread.ManagedThreadId, 
                                                   AppDomain.CurrentDomain.FriendlyName);
                                 AppDomain domain = AppDomain.CreateDomain("Domain2");
                                 DataRetriever d = (DataRetriever) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName,
                                                   "DataRetriever");
                                 return d.GetFormattedNumber(formatString); 
                               }); 
       Console.WriteLine(t2.Result);
   }
}

public class DataRetriever : MarshalByRefObject
{
   public string GetFormattedNumber(String format)
   {
      Thread thread = Thread.CurrentThread;
      Console.WriteLine("Current culture is {0}", thread.CurrentCulture);
      Console.WriteLine("Thread {0} is running in app domain '{1}'", 
                        thread.ManagedThreadId, 
                        AppDomain.CurrentDomain.FriendlyName);
      Random rnd = new Random();
      Double value = rnd.NextDouble() * 1000;
      return value.ToString(format);
   }
}
// The example displays output like the following:
//     The example is running on thread 1
//     The current culture is en-US
//     Changed the current culture to fr-FR.
//     
//     Executing a task asynchronously in a single appdomain:
//     Current culture is fr-FR
//     Thread 3 is running in app domain 'AsyncCulture4.exe'
//     93,48 €
//     
//     Executing a task synchronously in two appdomains:
//     Thread 4 is running in app domain 'AsyncCulture4.exe'
//     Current culture is fr-FR
//     Thread 4 is running in app domain 'Domain2'
//     288,66 €
Imports System.Globalization
Imports System.Runtime.Versioning
Imports System.Threading
Imports System.Threading.Tasks

<Assembly:TargetFramework(".NETFramework,Version=v4.6")>

Module Example
   Public Sub Main()
       Dim formatString As String = "C2"
       Console.WriteLine("The example is running on thread {0}", 
                         Thread.CurrentThread.ManagedThreadId)
       ' Make the current culture different from the system culture.
       Console.WriteLine("The current culture is {0}", 
                         CultureInfo.CurrentCulture.Name)
       If CultureInfo.CurrentCulture.Name = "fr-FR" Then
          Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US")
       Else
          Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR")
       End If

       Console.WriteLine("Changed the current culture to {0}.",
                         CultureInfo.CurrentCulture.Name)
       Console.WriteLine()
       
       ' Call an async delegate to format the values using one format string.
       Console.WriteLine("Executing a task asynchronously in the main appdomain:") 
       Dim t1 = Task.Run(Function()
                            Dim d As New DataRetriever()
                            Return d.GetFormattedNumber(formatString)
                         End Function)
       Console.WriteLine(t1.Result)
       Console.WriteLine() 
       
       Console.WriteLine("Executing a task synchronously in two appdomains:")
       Dim t2 = Task.Run(Function()
                            Console.WriteLine("Thread {0} is running in app domain '{1}'", 
                                              Thread.CurrentThread.ManagedThreadId, 
                                              AppDomain.CurrentDomain.FriendlyName)
                            Dim domain As AppDomain = AppDomain.CreateDomain("Domain2")
                            Dim d As DataRetriever = CType(domain.CreateInstanceAndUnwrap(GetType(Example).Assembly.FullName,
                                                                                          "DataRetriever"), DataRetriever)
                            Return d.GetFormattedNumber(formatString) 
                         End Function) 
       Console.WriteLine(t2.Result)
   End Sub
End Module

Public Class DataRetriever : Inherits MarshalByRefObject
   Public Function GetFormattedNumber(format As String) As String
      Dim thread As Thread = Thread.CurrentThread
      Console.WriteLine("Current culture is {0}", thread.CurrentCulture)
      Console.WriteLine("Thread {0} is running in app domain '{1}'", 
                        thread.ManagedThreadId, 
                        AppDomain.CurrentDomain.FriendlyName)
      Dim rnd As New Random()
      Dim value As Double = rnd.NextDouble() * 1000
      Return value.ToString(format)
   End Function
End Class
' The example displays output like the following:
'     The example is running on thread 1
'     The current culture is en-US
'     Changed the current culture to fr-FR.
'     
'     Executing a task asynchronously in a single appdomain:
'     Current culture is fr-FR
'     Thread 3 is running in app domain 'AsyncCulture4.exe'
'     93,48 €
'     
'     Executing a task synchronously in two appdomains:
'     Thread 4 is running in app domain 'AsyncCulture4.exe'
'     Current culture is fr-FR
'     Thread 4 is running in app domain 'Domain2'
'     288,66 €

CultureInfo 物件的序列化CultureInfo object serialization

CultureInfo序列化物件時,實際上儲存只NameUseUserOverrideWhen a CultureInfo object is serialized, all that is actually stored is Name and UseUserOverride. 它是只在環境中成功還原序列化所在的Name具有相同的意義。It is successfully de-serialized only in an environment where that Name has the same meaning. 下列三個範例顯示為什麼這不一定會這樣:The following three examples show why this is not always the case:

  • 如果CultureTypes屬性值是CultureTypes.InstalledWin32Cultures,如果在特定版本的 Windows 作業系統中引進該文化特性,不可能將它還原序列化舊版 Windows 上。If the CultureTypes property value is CultureTypes.InstalledWin32Cultures, and if that culture was first introduced in a particular version of the Windows operating system, it is not possible to deserialize it on an earlier version of Windows. 比方說,如果文化特性在 Windows 10 中引進,它無法還原序列化,在 Windows 8 上。For example, if a culture was introduced in Windows 10, it cannot be deserialized on Windows 8.

  • 如果CultureTypes值是CultureTypes.UserCustomCulture,並在其已還原序列化的電腦沒有安裝此使用者自訂文化特性,不可能將它還原序列化。If the CultureTypes value is CultureTypes.UserCustomCulture, and the computer on which it is de-serialized does not have this user custom culture installed, it is not possible to deserialize it.

  • 如果CultureTypes值是CultureTypes.ReplacementCultures,並在其已還原序列化的電腦沒有此取代的文化特性,還原序列化至相同的名稱,但不是所有相同的特性。If the CultureTypes value is CultureTypes.ReplacementCultures, and the computer on which it is de-serialized does not have this replacement culture, it de-serializes to the same name, but not all of the same characteristics. 例如,EN-US 是否取代的文化特性上的電腦,但不是能在電腦 B,以及是否CultureInfo物件指的此文化特性會在電腦 A 上序列化並在電腦 B 上還原序列化則沒有任何自訂的文化特性,傳輸。For example, if en-US is a replacement culture on computer A, but not on computer B, and if a CultureInfo object referring to this culture is serialized on computer A and de-serialized on computer B, then none of the custom characteristics of the culture are transmitted. 文化特性還原序列化成功,但具有不同的意義。The culture deserializes successfully, but with a different meaning.

控制台會覆寫Control Panel overrides

使用者可能選擇覆寫一些與目前的文化特性的 Windows [控制台] 的 [地區及語言選項] 部分透過相關聯的值。The user might choose to override some of the values associated with the current culture of Windows through the regional and language options portion of Control Panel. 比方說,使用者可能會選擇不同的格式顯示日期,或使用文化特性的預設值以外的貨幣。For example, the user might choose to display the date in a different format or to use a currency other than the default for the culture. 一般情況下,您的應用程式應該接受這些使用者覆寫。In general, your applications should honor these user overrides.

如果UseUserOverridetrue和指定的文化特性相符的 Windows,目前的文化特性CultureInfo會使用這些覆寫,包括使用者設定之屬性的DateTimeFormatInfo所傳回的執行個體DateTimeFormat屬性,和資料庫屬性NumberFormatInfo所傳回的執行個體NumberFormat屬性。If UseUserOverride is true and the specified culture matches the current culture of Windows, the CultureInfo uses those overrides, including user settings for the properties of the DateTimeFormatInfo instance returned by the DateTimeFormat property, and the properties of the NumberFormatInfo instance returned by the NumberFormat property. 如果使用者設定都與相關聯的文化特性不相容CultureInfo,例如,如果所選行事曆不是其中一個OptionalCalendars,不會定義方法的結果和屬性的值。If the user settings are incompatible with the culture associated with the CultureInfo, for example, if the selected calendar is not one of the OptionalCalendars, the results of the methods and the values of the properties are undefined.

替代排序次序Alternate sort orders

某些文化特性支援一個以上的排序次序。Some cultures support more than one sort order. 例如:For example:

  • 西班牙文 (西班牙) 文化特性中有兩個排序順序: 預設的國際排序順序,與傳統的排序順序。The Spanish (Spain) culture has two sort orders: the default international sort order, and the traditional sort order. 當您具現化CultureInfoES-ES 文化特性名稱,物件會使用國際排序順序。When you instantiate a CultureInfo object with the es-ES culture name, the international sort order is used. 當您具現化CultureInfoes-ES-tradnl 文化特性名稱,物件會使用傳統的排序順序。When you instantiate a CultureInfo object with the es-ES-tradnl culture name, the traditional sort order is used.

  • ZH-CN (中文 (簡體,中國)) 文化特性支援兩個排序順序: 依照拼音 (預設值) 和依照筆畫。The zh-CN (Chinese (Simplified, PRC)) culture supports two sort orders: by pronunciation (the default) and by stroke count. 當您具現化CultureInfoZH-CN 文化特性名稱,物件會使用預設排序順序。When you instantiate a CultureInfo object with the zh-CN culture name, the default sort order is used. 當您具現化CultureInfo0x00020804,區域識別項物件的字串會依照筆畫來排序。When you instantiate a CultureInfo object with a local identifier of 0x00020804, strings are sorted by stroke count.

下表列出支援的預設和替代排序次序的替代排序次序和識別項的文化特性。The following table lists the cultures that support alternate sort orders and the identifiers for the default and alternate sort orders.

文化特性名稱Culture name cultureCulture 預設排序名稱和識別碼Default sort name and identifier 替代的排序名稱和識別碼Alternate sort name and identifier
es-ESes-ES 西班牙文 (西班牙)Spanish (Spain) 國際電話號碼:0x00000C0AInternational: 0x00000C0A 傳統:0x0000040ATraditional: 0x0000040A
zh-TWzh-TW 中文 (台灣)Chinese (Taiwan) 筆劃數:0x00000404Stroke Count: 0x00000404 注音符號:0x00030404Bopomofo: 0x00030404
zh-CNzh-CN 中文 (中國)Chinese (PRC) 發音:0x00000804Pronunciation: 0x00000804 筆劃數:0x00020804Stroke Count: 0x00020804
zh-HKzh-HK 中文 (香港特別行政區)Chinese (Hong Kong SAR) 筆劃數:0x00000c04Stroke Count: 0x00000c04 筆劃數:0x00020c04Stroke Count: 0x00020c04
zh-SGzh-SG 中文 (新加坡)Chinese (Singapore) 發音:0x00001004Pronunciation: 0x00001004 筆劃數:0x00021004Stroke Count: 0x00021004
zh-MOzh-MO 中文 (澳門特別行政區)Chinese (Macao SAR) 發音:0x00001404Pronunciation: 0x00001404 筆劃數:0x00021404Stroke Count: 0x00021404
ja-JPja-JP 日文 (日本)Japanese (Japan) 預設:0x00000411Default: 0x00000411 Unicode:0x00010411Unicode: 0x00010411
ko-KRko-KR 韓文 (韓國)Korean (Korea) 預設:0x00000412Default: 0x00000412 韓文 Xwansung-Unicode:0x00010412Korean Xwansung - Unicode: 0x00010412
de-DEde-DE 德文 (德國)German (Germany) 字典中:0x00000407Dictionary: 0x00000407 電話簿排序 DIN:0x00010407Phone Book Sort DIN: 0x00010407
hu-HUhu-HU 匈牙利文 (匈牙利)Hungarian (Hungary) 預設:0x0000040eDefault: 0x0000040e 技術排序:0x0001040eTechnical Sort: 0x0001040e
ka-GEka-GE 喬治亞文 (喬治亞)Georgian (Georgia) 傳統:0x00000437Traditional: 0x00000437 現代的排序:0x00010437Modern Sort: 0x00010437

目前的文化特性和 UWP 應用程式The current culture and UWP apps

在通用 Windows 平台 (UWP) 應用程式中,CurrentCultureCurrentUICulture屬性是讀寫,就如同它們在.NET Framework 和.NET Core 應用程式中。In Universal Windows Platform (UWP) apps, the CurrentCulture and CurrentUICulture properties are read-write, just as they are in .NET Framework and .NET Core apps. 不過,UWP 應用程式會辨識之單一文化特性。However, UWP apps recognize a single culture. CurrentCultureCurrentUICulture中的第一個值的屬性對應Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages集合。The CurrentCulture and CurrentUICulture properties map to the first value in the Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages collection.

在.NET Framework 和.NET Core 應用程式中目前的文化特性是每個執行緒設定,而CurrentCultureCurrentUICulture屬性會反映的文化特性和 UI 文化特性只有目前的執行緒。In .NET Framework and .NET Core apps, the current culture is a per-thread setting, and the CurrentCulture and CurrentUICulture properties reflect the culture and UI culture of the current thread only. 在 UWP 應用程式,目前的文化特性會對應至Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages集合,而這是全域設定。In UWP apps, the current culture maps to the Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages collection, which is a global setting. 設定CurrentCultureCurrentUICulture屬性也會變更整個應用程式的文化特性; 無法設定每個執行緒為基礎的文化特性。Setting the CurrentCulture or CurrentUICulture property changes the culture of the entire app; culture cannot be set on a per-thread basis.

建構函式

CultureInfo(Int32) CultureInfo(Int32) CultureInfo(Int32) CultureInfo(Int32)

根據文化特性識別項所指定的文化特性,初始化 CultureInfo 類別的新執行個體。Initializes a new instance of the CultureInfo class based on the culture specified by the culture identifier.

CultureInfo(Int32, Boolean) CultureInfo(Int32, Boolean) CultureInfo(Int32, Boolean) CultureInfo(Int32, Boolean)

根據文化特性識別項所指定的文化特性,並根據指定是否要使用系統中使用者選取的文化特性設定的布林值,初始化 CultureInfo 類別的新執行個體。Initializes a new instance of the CultureInfo class based on the culture specified by the culture identifier and on the Boolean that specifies whether to use the user-selected culture settings from the system.

CultureInfo(String) CultureInfo(String) CultureInfo(String) CultureInfo(String)

根據名稱所指定的文化特性,初始化 CultureInfo 類別的新執行個體。Initializes a new instance of the CultureInfo class based on the culture specified by name.

CultureInfo(String, Boolean) CultureInfo(String, Boolean) CultureInfo(String, Boolean) CultureInfo(String, Boolean)

根據名稱所指定的文化特性,並根據指示是否要從系統中使用使用者選取的文化特性設定的布林值,初始化 CultureInfo 類別的新執行個體。Initializes a new instance of the CultureInfo class based on the culture specified by name and on the Boolean that specifies whether to use the user-selected culture settings from the system.

屬性

Calendar Calendar Calendar Calendar

取得文化特性使用的預設曆法。Gets the default calendar used by the culture.

CompareInfo CompareInfo CompareInfo CompareInfo

取得 CompareInfo,定義此文化特性如何比較字串。Gets the CompareInfo that defines how to compare strings for the culture.

CultureTypes CultureTypes CultureTypes CultureTypes

取得和目前 CultureInfo 物件關聯的文化特性類型。Gets the culture types that pertain to the current CultureInfo object.

CurrentCulture CurrentCulture CurrentCulture CurrentCulture

取得或設定 CultureInfo 物件,這個物件代表目前執行緒使用的文化特性。Gets or sets the CultureInfo object that represents the culture used by the current thread.

CurrentUICulture CurrentUICulture CurrentUICulture CurrentUICulture

取得或設定 CultureInfo 物件,此物件代表 Resource Manager 用於執行階段查詢特定文化特性資源的目前使用者介面文化特性。Gets or sets the CultureInfo object that represents the current user interface culture used by the Resource Manager to look up culture-specific resources at run time.

DateTimeFormat DateTimeFormat DateTimeFormat DateTimeFormat

取得或設定 DateTimeFormatInfo,定義日期和時間在文化特性上適當的顯示格式。Gets or sets a DateTimeFormatInfo that defines the culturally appropriate format of displaying dates and times.

DefaultThreadCurrentCulture DefaultThreadCurrentCulture DefaultThreadCurrentCulture DefaultThreadCurrentCulture

取得或設定目前應用程式定義域中之執行緒的預設文化特性。Gets or sets the default culture for threads in the current application domain.

DefaultThreadCurrentUICulture DefaultThreadCurrentUICulture DefaultThreadCurrentUICulture DefaultThreadCurrentUICulture

取得或設定目前應用程式定義域中之執行緒的預設 UI 文化特性。Gets or sets the default UI culture for threads in the current application domain.

DisplayName DisplayName DisplayName DisplayName

取得完整當地語系化文化特性名稱。Gets the full localized culture name.

EnglishName EnglishName EnglishName EnglishName

取得格式為 languagefull [country/regionfull] 的英文文化特性名稱。Gets the culture name in the format languagefull [country/regionfull] in English.

IetfLanguageTag IetfLanguageTag IetfLanguageTag IetfLanguageTag

已取代。Deprecated. 取得語言的 RFC 4646 標準識別。Gets the RFC 4646 standard identification for a language.

InstalledUICulture InstalledUICulture InstalledUICulture InstalledUICulture

取得 CultureInfo,表示作業系統所安裝的文化特性。Gets the CultureInfo that represents the culture installed with the operating system.

InvariantCulture InvariantCulture InvariantCulture InvariantCulture

取得與文化特性無關的 (不變的) CultureInfo 物件。Gets the CultureInfo object that is culture-independent (invariant).

IsNeutralCulture IsNeutralCulture IsNeutralCulture IsNeutralCulture

取得值,指出目前 CultureInfo 是否表示中性文化特性。Gets a value indicating whether the current CultureInfo represents a neutral culture.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

取得值,指出目前 CultureInfo 是否為唯讀。Gets a value indicating whether the current CultureInfo is read-only.

KeyboardLayoutId KeyboardLayoutId KeyboardLayoutId KeyboardLayoutId

取得使用中的輸入地區設定識別項 (Input Locale Identifier)。Gets the active input locale identifier.

LCID LCID LCID LCID

取得目前 CultureInfo 的文化特性識別項。Gets the culture identifier for the current CultureInfo.

Name Name Name Name

取得格式為 languagecode2-country/regioncode2 的文化特性名稱。Gets the culture name in the format languagecode2-country/regioncode2.

NativeName NativeName NativeName NativeName

取得文化特性設定為要顯示的文化特性名稱,由語言、國家/地區和選擇性 (Optional) 指令碼組成。Gets the culture name, consisting of the language, the country/region, and the optional script, that the culture is set to display.

NumberFormat NumberFormat NumberFormat NumberFormat

取得或設定 NumberFormatInfo,定義數字、貨幣和百分比在文化特性上適當的顯示格式。Gets or sets a NumberFormatInfo that defines the culturally appropriate format of displaying numbers, currency, and percentage.

OptionalCalendars OptionalCalendars OptionalCalendars OptionalCalendars

取得可為文化特性所使用的曆法清單。Gets the list of calendars that can be used by the culture.

Parent Parent Parent Parent

取得 CultureInfo,表示目前 CultureInfo 的父文化特性。Gets the CultureInfo that represents the parent culture of the current CultureInfo.

TextInfo TextInfo TextInfo TextInfo

取得 TextInfo,定義與文化特性相關的書寫系統。Gets the TextInfo that defines the writing system associated with the culture.

ThreeLetterISOLanguageName ThreeLetterISOLanguageName ThreeLetterISOLanguageName ThreeLetterISOLanguageName

取得目前 CultureInfo 的語言的 ISO 639-2 三個字母代碼。Gets the ISO 639-2 three-letter code for the language of the current CultureInfo.

ThreeLetterWindowsLanguageName ThreeLetterWindowsLanguageName ThreeLetterWindowsLanguageName ThreeLetterWindowsLanguageName

取得該語言在 Windows API 定義中的三個字母代碼。Gets the three-letter code for the language as defined in the Windows API.

TwoLetterISOLanguageName TwoLetterISOLanguageName TwoLetterISOLanguageName TwoLetterISOLanguageName

取得目前 CultureInfo 的語言的 ISO 639-1 兩個字母代碼。Gets the ISO 639-1 two-letter code for the language of the current CultureInfo.

UseUserOverride UseUserOverride UseUserOverride UseUserOverride

取得值,指出目前 CultureInfo 是否使用使用者選取的文化特性設定。Gets a value indicating whether the current CultureInfo object uses the user-selected culture settings.

方法

ClearCachedData() ClearCachedData() ClearCachedData() ClearCachedData()

重新整理已快取的文化特性相關資訊。Refreshes cached culture-related information.

Clone() Clone() Clone() Clone()

建立目前 CultureInfo 的複本。Creates a copy of the current CultureInfo.

CreateSpecificCulture(String) CreateSpecificCulture(String) CreateSpecificCulture(String) CreateSpecificCulture(String)

建立 CultureInfo,代表與指定名稱相關的特定文化特性。Creates a CultureInfo that represents the specific culture that is associated with the specified name.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定物件是否與目前 CultureInfo 為相同的文化特性。Determines whether the specified object is the same culture as the current CultureInfo.

GetConsoleFallbackUICulture() GetConsoleFallbackUICulture() GetConsoleFallbackUICulture() GetConsoleFallbackUICulture()

在預設的圖形使用者介面 (Graphic User Interface,GUI) 的文化特性不適合主控台應用程式 (Console Application) 時,取得適合的替代使用者介面文化特性。Gets an alternate user interface culture suitable for console applications when the default graphic user interface culture is unsuitable.

GetCultureInfo(Int32) GetCultureInfo(Int32) GetCultureInfo(Int32) GetCultureInfo(Int32)

使用指定的文化特性識別項,擷取已快取的唯讀文化特性執行個體。Retrieves a cached, read-only instance of a culture by using the specified culture identifier.

GetCultureInfo(String) GetCultureInfo(String) GetCultureInfo(String) GetCultureInfo(String)

使用指定的文化特性名稱,擷取已快取的唯讀文化特性執行個體。Retrieves a cached, read-only instance of a culture using the specified culture name.

GetCultureInfo(String, String) GetCultureInfo(String, String) GetCultureInfo(String, String) GetCultureInfo(String, String)

擷取文化特性的快取、唯讀執行個體。Retrieves a cached, read-only instance of a culture. 這些參數會指定文化特性,這個文化特性使用另一個文化特性所指定的 TextInfoCompareInfo 物件來初始化。Parameters specify a culture that is initialized with the TextInfo and CompareInfo objects specified by another culture.

GetCultureInfoByIetfLanguageTag(String) GetCultureInfoByIetfLanguageTag(String) GetCultureInfoByIetfLanguageTag(String) GetCultureInfoByIetfLanguageTag(String)

已取代。Deprecated. 擷取唯讀的 CultureInfo 物件,其語言特性是透過指定的 RFC 4646 語言標籤所辨識。Retrieves a read-only CultureInfo object having linguistic characteristics that are identified by the specified RFC 4646 language tag.

GetCultures(CultureTypes) GetCultures(CultureTypes) GetCultures(CultureTypes) GetCultures(CultureTypes)

取得支援的文化特性清單,此清單經過指定的 CultureTypes 參數篩選。Gets the list of supported cultures filtered by the specified CultureTypes parameter.

GetFormat(Type) GetFormat(Type) GetFormat(Type) GetFormat(Type)

取得定義如何格式化指定型別的物件。Gets an object that defines how to format the specified type.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為目前 CultureInfo 的雜湊函式,適合於雜湊演算法和資料結構 (如雜湊資料表)。Serves as a hash function for the current CultureInfo, suitable for hashing algorithms and data structures, such as a hash table.

GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ReadOnly(CultureInfo) ReadOnly(CultureInfo) ReadOnly(CultureInfo) ReadOnly(CultureInfo)

傳回指定 CultureInfo 物件的唯讀包裝函式。Returns a read-only wrapper around the specified CultureInfo object.

ToString() ToString() ToString() ToString()

傳回包含目前 CultureInfo 名稱的字串,其格式為 languagecode2-country/regioncode2Returns a string containing the name of the current CultureInfo in the format languagecode2-country/regioncode2.

適用於

另請參閱