CultureInfo CultureInfo CultureInfo CultureInfo Class

定义

提供有关特定区域性(对于非托管代码开发,则称为“区域设置”)的信息。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.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



'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. 此类还DateTimeFormatInfo提供对CompareInfoNumberFormatInfo、和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. 类直接或间接用于格式化、分析或操作区域性特定数据的类, String如、 DateTimeDateTimeOffset和数值类型。 CultureInfoThe 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 2 字母小写区域性代码的组合,以及与国家或地区关联的 ISO 3166 2 字母大写子区域性代码。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是两个字母的语言代码,国家/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. 例如,对于日语(日本)和 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-Cyrl-UZ for 乌兹别克语(西里尔语、乌兹别克斯坦)。An example of this type of culture name is uz-Cyrl-UZ for Uzbek (Cyrillic, Uzbekistan). 在 windows Vista 之前的 windows 操作系统上,包含脚本的区域性名称使用模式为 languagecode2-country/regioncode2-scripttag,例如,uz-uz-Cyrl for 乌兹别克语(西里尔语,乌兹别克斯坦)。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 指定法语的非特定区域性,而 de 指定了德语的非特定区域性。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-chs-Hans 的区域性中文(简体)、名为 zh-chs-Zh-hant 的中文(繁体)是非特定区域性。The cultures Chinese (Simplified), named zh-Hans, and Chinese (Traditional), named zh-Hant, are neutral cultures. 区域性名称表示当前标准,并且应使用,除非您有理由使用旧名称 zh-chs 和 zh-chs-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 47 定义的标准。Culture 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 区域设置生成器工具添加自己的自定义区域性。Users add their own custom cultures using the Microsoft Locale Builder tool. Microsoft 区域设置生成器使用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 是特定法语(法国)区域性的名称。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.

只能为固定NumberFormatInfo区域性或特定区域性创建或,而不能为非特定区域性创建或。DateTimeFormatInfoA DateTimeFormatInfo or a NumberFormatInfo can be created only for the invariant culture or for specific cultures, not for neutral cultures.

如果DateTimeFormatInfo.Calendar DateTimeFormatInfo.NativeCalendarName为,但Thread.CurrentCulture未设置为zh-chs, DateTimeFormatInfo.GetAbbreviatedEraName则和将返回一个空字符串("")。 DateTimeFormatInfo.GetEraName TaiwanCalendarIf 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-chs" 或中文(简体,中国)、zh-chs 或中文(繁体,台湾)是 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-chs" 是 "zh-chs-Hans" 区域性的别名,"zh-chs-隶书" 是 "zh-chs-Zh-hant" 区域性的别名。"zh-CN" is an alias for the "zh-Hans-CN" culture, and "zh-TW" is an alias for the "zh-Hant-TW" culture. 对方法的调用不返回化名为的GetCultures区域性,它可能具有不同于其 Windows 对应Parent项的不同属性值(包括不同的区域性)。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. 对于 zh-chs 和 zh-chs,这些 differenes 包括以下各项:For the zh-CN and zh-TW cultures, these differenes include the following:

  • 在 Windows 系统中,"zh-chs" 区域性的父区域性为 "zh-chs-Hans","zh-chs" 区域性的父区域性为 "zh-chs-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-chs"。The parent culture of both these cultures is "zh". 在 Unix 系统上,这两个区域性的父代为 "zh-chs"。On Unix systems, the parents of both cultures are "zh". 这意味着,如果不为 "zh-chs" 或 "zh-chs" 区域性提供区域性特定的资源,但确实为非特定 "zh-chs" 或 "zh-chs-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-chs-Hans" 或 "zh-chs-zh-hant"。On Unix systems, you must explicitly set the thread's CurrentUICulture to either "zh-Hans" or "zh-Hant".

  • 在 Windows 系统上, CultureInfo.Equals对表示 "zh-chs" 区域性的实例调用,并向其传递一个 "zh-chs-Hans" 实例返回。 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-chs" CultureInfo实例上调用并向其传递一个 "zh-chs-zh-hant-隶书" 实例。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 CultureInfoInstantiate 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对象是否反映用户重写(如果新区域性与当前 Windows 区域性相同)。 CultureInfo(String, Boolean)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. 将对象分配给 .net CultureInfo.CurrentCulture Core CultureInfo.CurrentUICulture上的或属性,并 .NET Framework 4.6 及更高版本。 CultureInfoAssign 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 和更早的版本中,youc CultureInfo将对象分配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 4.5.NET Framework 4.5的 .NET Framework 版本中,确保主应用程序线程与所有其他工作线程共享相同的区域性的最常见方法是:传递应用程序范围的区域性的名称或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 €

您可以通过调用ThreadPool.QueueUserWorkItem(WaitCallback, Object)方法以类似方式设置线程池线程的区域性和 UI 区域性。You can set the culture and UI culture of thread pool threads in a similar manner by calling the ThreadPool.QueueUserWorkItem(WaitCallback, Object) method.

从开始CultureInfo DefaultThreadCurrentCulture DefaultThreadCurrentUICulture ,你可以通过将表示区域性的对象分配给和属性,来更直接地设置应用程序域中所有线程的区域性和 UI 区域性。 .NET Framework 4.5.NET Framework 4.5Starting 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 €

警告

DefaultThreadCurrentCulture尽管和DefaultThreadCurrentUICulture属性是静态成员,但它们仅定义了在设置这些属性值时当前为当前应用程序域的默认区域性和默认 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 区域性没有显式分配有区域性,则这些线程的区域性和 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. 因此,建议你始终设置主应用程序线程的区域性,而不是DefaultThreadCurrentCulture依赖于和DefaultThreadCurrentUICulture属性来更改它。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 区域性设置为法语(法国),然后使用AppDomainSetupAppDomainInitializer和委托将新的应用程序域中的默认区域性和 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. DefaultThreadCurrentCulture请注意,当DefaultThreadCurrentUICulture进行方法调用时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.6面向。It 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 4.6.NET Framework 4.6的 .NET Framework 版本的应用,或对于未面向特定版本 .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。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 4.5.NET Framework 4.5版本 .NET Framework 的应用程序和更高版本DefaultThreadCurrentCulture ,但在.NET Framework 4.6.NET Framework 4.6之前,你可以使用和DefaultThreadCurrentUICulture属性来确保调用线程的区域性用于异步任务在线程池线程上执行。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. 它使用单个GetFormattedNumber方法定义DataRetriever一个类,该方法返回格式设置为货币值的1到1000之间的随机双精度浮点数。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

序列化Name UseUserOverride对象时,实际上存储的是和。 CultureInfoWhen 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.InstalledWin32Cultures,且该区域性首次在 windows 操作系统的特定版本中引入,则不能在早期版本的 windows 上对其进行反序列化。 CultureTypesIf 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.UserCustomCulture,并且对其进行反序列化的计算机未安装此用户自定义区域性,则无法对其进行反序列化。 CultureTypesIf 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.ReplacementCultures,并且反序列化它的计算机没有此替换区域性,则会将其反序列化到相同的名称,但不是所有相同的特性。 CultureTypesIf 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 是计算机 a 上的替代区域性,但不在计算机 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.

如果UseUserOverride CultureInfotrue ,并且指定的区域性与 Windows 的当前区域性匹配,则将使用这些替代, DateTimeFormatInfo包括DateTimeFormat属性返回的实例的属性的用户设置。属性NumberFormat返回的NumberFormatInfo实例的属性。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. 使用 es 区域性名称CultureInfo实例化对象时,将使用国际排序顺序。When you instantiate a CultureInfo object with the es-ES culture name, the international sort order is used. 使用 tradnl 区域性名称CultureInfo实例化对象时,使用传统排序顺序。When you instantiate a CultureInfo object with the es-ES-tradnl culture name, the traditional sort order is used.

  • Zh-chs (简体中文,PRC)区域性支持两种排序顺序:按发音(默认)和按笔划计数。The zh-CN (Chinese (Simplified, PRC)) culture supports two sort orders: by pronunciation (the default) and by stroke count. 使用 zh-chs-CN CultureInfo区域性名称实例化对象时,将使用默认的排序顺序。When you instantiate a CultureInfo object with the zh-CN culture name, the default sort order is used. 当使用本地标识符CultureInfo 0x00020804 来实例化对象时,字符串将按笔画排序。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-chs-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 电话簿排序方式: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. 和属性映射到 DefaultContext 集合中的第一个值。 windows.applicationmodel.resources.core 集合中的第一个值。 CurrentCulture CurrentUICultureThe 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集合,该集合是全局设置的集合。In UWP apps, the current culture maps to the Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages collection, which is a global setting. CurrentCulture设置或CurrentUICulture属性会更改整个应用的区域性; 不能在每个线程的基础上设置区域性。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

获取为区域性定义如何比较字符串的 CompareInfoGets 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 对象,该对象表示资源管理器在运行时查找区域性特定资源时所用的当前用户接口区域性。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

获取表示操作系统中安装的区域性的 CultureInfoGets 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

获取活动的输入法区域设置标识符。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

获取为区域性设置的显示名称,它由语言、国家/地区以及可选的书写符号组成。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 的父区域性的 CultureInfoGets the CultureInfo that represents the parent culture of the current CultureInfo.

TextInfo TextInfo TextInfo TextInfo

获取定义与区域性关联的书写体系的 TextInfoGets 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)

创建表示与指定名称关联的特定区域性的 CultureInfoCreates 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()

如果默认的图形用户界面区域性不合适,则获取适合控制台应用程序的备用用户界面区域性。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 的浅表副本。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/regioncode2。Returns a string containing the name of the current CultureInfo in the format languagecode2-country/regioncode2.

适用于

另请参阅