CultureInfo クラス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
特定のカルチャ (アンマネージ コードの開発では "ロケール" と呼ばれます) に関する情報を提供します。 この情報には、カルチャの名前、表記体系、使用する暦、文字列の並べ替え順序、および日付と数値の書式が含まれます。
public ref class CultureInfo : IFormatProvider
public ref class CultureInfo : ICloneable, IFormatProvider
public class CultureInfo : IFormatProvider
public class CultureInfo : ICloneable, IFormatProvider
[System.Serializable]
public class CultureInfo : ICloneable, IFormatProvider
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class CultureInfo : ICloneable, IFormatProvider
type CultureInfo = class
interface IFormatProvider
type CultureInfo = class
interface ICloneable
interface IFormatProvider
[<System.Serializable>]
type CultureInfo = class
interface ICloneable
interface IFormatProvider
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type CultureInfo = class
interface ICloneable
interface IFormatProvider
Public Class CultureInfo
Implements IFormatProvider
Public Class CultureInfo
Implements ICloneable, IFormatProvider
- 継承
-
CultureInfo
- 属性
- 実装
例
次の例は、国際並べ替えを使用してスペイン語 (スペイン) のオブジェクトを作成し、従来の並べ替えを使用して別CultureInfoのオブジェクトを作成CultureInfoする方法を示しています。
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 、言語、サブ言語、国/地域、カレンダー、特定のカルチャに関連付けられている規則など、カルチャ固有の情報を提供します。 このクラスは、、NumberFormatInfoCompareInfoおよび TextInfo オブジェクトのカルチャ固有のDateTimeFormatInfoインスタンスへのアクセスも提供します。 これらのオブジェクトには、大文字と小文字の区別、日付と数値の書式設定、文字列の比較など、カルチャ固有の操作に必要な情報が含まれています。 クラスはCultureInfo、数値型などのStringDateTimeDateTimeOffsetカルチャ固有のデータを書式設定、解析、または操作するクラスによって直接または間接的に使用されます。
このセクションの内容:
カルチャ名と識別子
インバリアント、ニュートラル、および特定のカルチャ
カスタム カルチャ
動的カルチャ データ
CultureInfo とカルチャ データ
現在のカルチャと現在の UI カルチャ
すべてのカルチャを取得する
カルチャとスレッド
カルチャとアプリケーション ドメイン
カルチャとタスクベースの非同期操作
CultureInfo オブジェクトのシリアル化
コントロール パネルオーバーライド
代替並べ替え順序
カルチャと Windows アプリ
カルチャ名と識別子
クラスは CultureInfo 、RFC 4646 に基づいて、カルチャごとに一意の名前を指定します。 名前は、言語に関連付けられた ISO 639 の 2 文字または 3 文字の小文字カルチャ コードと、国または地域に関連付けられた ISO 3166 の 2 文字の大文字サブカルチャ コードの組み合わせです。 さらに、.NET Framework 4 以降を対象とし、Windows 10以降で実行されているアプリでは、有効な BCP-47 言語タグに対応するカルチャ名がサポートされます。
注意
カルチャ名が クラス コンストラクターまたは や などの CreateSpecificCulture メソッドに渡される場合、その大文字と CultureInfo小文字は重要ではありません。
RFC 4646 に基づくカルチャ名の形式は です languagecode2
-country/regioncode2
。ここで languagecode2
、 は 2 文字の言語コードで、 country/regioncode2
2 文字のサブカルチャ コードです。 たとえば、ja-JP
日本語 (日本) とen-US
英語 (米国) などです。 2 文字の言語コードを使用できない場合は、ISO 639-3 で定義されている 3 文字のコードが使用されます。
一部のカルチャ名では、ISO 15924 スクリプトも指定されます。 たとえば、Cyrl はキリル文字スクリプトを指定し、Latn はラテン文字スクリプトを指定します。 スクリプトを含むカルチャ名では、 パターンlanguagecode2
--scripttag
country/regioncode2
を使用します。 この種類のカルチャ名の例として、 uz-Cyrl-UZ
ウズベク語 (キリル文字、ウズベキスタン) があります。 Windows Vista より前の Windows オペレーティング システムでは、スクリプトを含むカルチャ名は、たとえばウズベク語 (キリル文字、ウズベキスタン) の場合など、 というパターンlanguagecode2
-scripttag
-country/regioncode2
を使用します。 uz-UZ-Cyrl
ニュートラル カルチャは、2 文字の小文字の言語コードでのみ指定されます。 たとえば、 fr
はフランス語のニュートラル カルチャを指定し de
、ドイツ語のニュートラル カルチャを指定します。
注意
この規則と矛盾する 2 つのカルチャ名があります。 という名前 zh-Hans
の中国語 (簡体字)、および中国語 (繁体字) というカルチャ zh-Hant
は、ニュートラル カルチャです。 カルチャ名は現在の標準を表し、古い名前 zh-CHS
と zh-CHT
を使用する理由がない限り使用する必要があります。
カルチャ識別子は標準の国際数値省略形であり、インストールされているカルチャの 1 つを一意に識別するために必要なコンポーネントを持ちます。 アプリケーションでは、定義済みのカルチャ識別子を使用することも、カスタム識別子を定義することもできます。
特定の定義済みのカルチャ名と識別子は、名前空間内のこのクラスと他の System.Globalization クラスによって使用されます。 Windows システムのカルチャの詳細については、Windows でサポートされている言語/地域名の一覧の言語タグ列を参照してください。 カルチャ名は、BCP 47 によって定義されている標準に準拠します。
カルチャ名と識別子は、特定のコンピューターで見つかるカルチャのサブセットのみを表します。 Windows バージョンまたはサービス パックは、使用可能なカルチャを変更できます。 アプリケーションでは、 クラスを使用してカスタム カルチャを CultureAndRegionInfoBuilder 追加できます。 ユーザーは、 Microsoft Locale Builder ツールを使用して独自のカスタム カルチャを追加できます。 Microsoft Locale Builder は、 クラスを使用して CultureAndRegionInfoBuilder
マネージド コードで記述されます。
いくつかの個別の名前はカルチャに密接に関連付けられています。特に、次のクラス メンバーに関連付けられている名前です。
インバリアント、ニュートラル、および特定のカルチャ
カルチャは一般に、インバリアント カルチャ、ニュートラル カルチャ、および特定のカルチャの 3 つのセットにグループ化されます。
インバリアント カルチャはカルチャに依存しません。 アプリケーションでは、空の文字列 ("") またはその識別子を使用して、名前によって不変カルチャを指定します。 InvariantCulture は、インバリアント カルチャのインスタンスを定義します。 これは英語に関連付けられていますが、国/地域には関連付けされません。 カルチャを必要とする名前空間のほぼすべてのメソッドで Globalization
使用されます。
ニュートラル カルチャは、言語に関連付けられているが、国/地域には関連付けられていないカルチャです。 特定のカルチャは、言語と国/地域に関連付けられているカルチャです。 たとえば、 fr
はフランス語カルチャのニュートラル名で fr-FR
、 は特定のフランス語 (フランス) カルチャの名前です。 中国語 (簡体字) と中国語 (繁体字) も中立的なカルチャと見なされることに注意してください。
ニュートラル カルチャのクラスの CompareInfo インスタンスを作成することは推奨されません。含まれるデータは任意であるためです。 データを表示および並べ替えるには、言語と地域の両方を指定します。 さらに、 Name ニュートラル カルチャ用に CompareInfo 作成された オブジェクトの プロパティは、国のみを返し、リージョンは含まれません。
定義されたカルチャには、特定のカルチャの親がニュートラル カルチャであり、ニュートラル カルチャの親がインバリアント カルチャである階層があります。 プロパティには Parent 、特定のカルチャに関連付けられているニュートラル カルチャが含まれています。 カスタム カルチャでは、このパターンに Parent 準拠して プロパティを定義する必要があります。
オペレーティング システムで特定のカルチャのリソースを使用できない場合は、関連付けられているニュートラル カルチャのリソースが使用されます。 ニュートラル カルチャのリソースを使用できない場合は、メイン アセンブリに埋め込まれているリソースが使用されます。 リソース フォールバック プロセスの詳細については、「リソースの パッケージ化とデプロイ」を参照してください。
Windows API のロケールの一覧は、.NET でサポートされているカルチャの一覧とは若干異なります。 たとえば、p/invoke メカニズムを使用して Windows との相互運用性が必要な場合、アプリケーションはオペレーティング システムに定義されている特定のカルチャを使用する必要があります。 特定のカルチャを使用すると、同等の Windows ロケールとの一貫性が確保されます。これは と同じ LCIDロケール識別子で識別されます。
DateTimeFormatInfoまたは はNumberFormatInfo、インバリアント カルチャまたは特定のカルチャに対してのみ作成でき、ニュートラル カルチャの場合は作成できません。
が ですが、 Thread.CurrentCulture が にzh-TW
設定されていない場合DateTimeFormatInfo.Calendarは、DateTimeFormatInfo.NativeCalendarNameDateTimeFormatInfo.GetEraNameおよび DateTimeFormatInfo.GetAbbreviatedEraName 空の文字列 ("") が返TaiwanCalendarされます。
カスタム カルチャ
Windows では、カスタム ロケールを作成できます。 詳細については、「 カスタム ロケール」を参照してください。
CultureInfo とカルチャ データ
.NET は、実装、プラットフォーム、バージョンに応じて、さまざまなソースの 1 つからカルチャ データを派生させます。
.NET Framework 3.5 以前のバージョンでは、カルチャ データは Windows オペレーティング システムと.NET Frameworkの両方によって提供されます。
.NET Framework 4 以降のバージョンでは、カルチャ データは Windows オペレーティング システムによって提供されます。
Windows で実行されているすべてのバージョンの .NET Core では、カルチャ データは Windows オペレーティング システムによって提供されます。
Unix プラットフォームで実行されているすべてのバージョンの .NET Core では、カルチャ データは International Components for Unicode (ICU) ライブラリによって提供されます。 ICU ライブラリの特定のバージョンは、個々のオペレーティング システムによって異なります。
このため、特定の .NET 実装、プラットフォーム、またはバージョンで使用できるカルチャは、別の .NET 実装、プラットフォーム、またはバージョンでは使用できない場合があります。
一部のオブジェクトは CultureInfo
、基になるプラットフォームによって異なります。 特に、、 zh-CN
または中国語 (簡体字、中国)、 zh-TW
または中国語 (繁体字、台湾) は、Windows システムでは使用できるカルチャですが、Unix システムではエイリアス化されたカルチャです。 "zh-CN" は "zh-Hans-CN" カルチャの別名であり、"zh-TW" は "zh-Hant-TW" カルチャの別名です。 エイリアス化されたカルチャは、 メソッドの呼び出しによって返されず、Windows に対応する GetCultures カルチャとは異なるカルチャを含む、異なる Parent プロパティ値を持つ場合があります。 と zh-TW
カルチャのzh-CN
場合、これらの相違点には次のものが含まれます。
Windows システムでは、"zh-CN" カルチャの親カルチャは "zh-Hans" で、"zh-TW" カルチャの親カルチャは "zh-Hant" です。 これらの両方のカルチャの親カルチャは "zh" です。 Unix システムでは、両方のカルチャの親は "zh" です。 つまり、"zh-CN" または "zh-TW" カルチャにカルチャ固有のリソースを提供せず、ニュートラルな "zh-Hans" カルチャまたは "zh-Hant" カルチャのリソースを提供する場合、アプリケーションは Windows ではニュートラル カルチャのリソースを読み込みますが、Unix では読み込まれません。 Unix システムでは、スレッドの CurrentUICulture を "zh-Hans" または "zh-Hant" に明示的に設定する必要があります。
Windows システムでは、"zh-CN" カルチャを表す インスタンスで を呼び出 CultureInfo.Equals し、"zh-Hans-CN" インスタンスを渡すと が返されます
true
。 Unix システムでは、メソッド呼び出しは を返しますfalse
。 この動作は、"zh-TW" CultureInfo インスタンスで を呼び出Equalsし、それを "zh-Hant-Tw" インスタンスに渡すことにも適用されます。
動的カルチャ データ
インバリアント カルチャを除き、カルチャ データは動的です。 これは、定義済みのカルチャでも当てはまります。 たとえば、国または地域で新しい通貨を採用したり、単語のスペルを変更したり、優先カレンダーを変更したり、カルチャ定義が変更されてこれを追跡したりします。 カスタム カルチャは予告なしに変更される可能性があり、特定のカルチャはカスタム置換カルチャによってオーバーライドされる可能性があります。 また、以下で説明するように、個々のユーザーは文化的な好みをオーバーライドできます。 アプリケーションでは、常に実行時にカルチャ データを取得する必要があります。
注意事項
データを保存するときは、アプリケーションでインバリアント カルチャ、バイナリ形式、または特定のカルチャに依存しない形式を使用する必要があります。 インバリアント カルチャ以外の特定のカルチャに関連付けられている現在の値に従って保存されたデータは、読み取り不能になるか、カルチャが変更された場合に意味が変わる可能性があります。
現在のカルチャと現在の UI カルチャ
.NET アプリケーション内のすべてのスレッドには、現在のカルチャと現在の UI カルチャがあります。 現在のカルチャは、日付、時刻、数値、通貨値の書式設定規則、テキストの並べ替え順序、大文字と小文字の区別の規則、および文字列の比較方法を決定します。 現在の UI カルチャは、実行時にカルチャ固有のリソースを取得するために使用されます。
注意
現在と現在の UI カルチャがスレッドごとにどのように決定されるかについては、「 カルチャとスレッド 」セクションを参照してください。 新しいアプリケーション ドメインで実行されているスレッドと、アプリケーション ドメインの境界を越えるスレッドで現在と現在の UI カルチャがどのように決定されるかについては、「 カルチャとアプリケーション ドメイン 」セクションを参照してください。 タスク ベースの非同期操作を実行するスレッドで現在と現在の が決定される方法については、「 カルチャとタスクベースの非同期操作 」セクションを参照してください。
現在のカルチャの詳細については、プロパティのトピックを CultureInfo.CurrentCulture 参照してください。 現在の UI カルチャの詳細については、プロパティのトピックを CultureInfo.CurrentUICulture 参照してください。
現在の UI カルチャと現在の UI カルチャの取得
現在のカルチャを CultureInfo 表す オブジェクトは、次の 2 つの方法のいずれかで取得できます。
プロパティの CultureInfo.CurrentCulture 値を取得します。
Thread.CurrentThread.CurrentCulture プロパティの値を取得します。
次の例では、両方のプロパティ値を取得し、それらを比較して等しいことを示し、現在のカルチャの名前を表示します。
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 2 つの方法のいずれかで、現在の UI カルチャを表す オブジェクトを取得できます。
プロパティの CultureInfo.CurrentUICulture 値を取得します。
Thread.CurrentThread.CurrentUICulture プロパティの値を取得します。
次の例では、両方のプロパティ値を取得し、それらを比較して等しいことを示し、現在の UI カルチャの名前を表示します。
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 カルチャを設定する
スレッドのカルチャと UI カルチャを変更するには、次の操作を行います。
クラス コンストラクターを CultureInfo 呼び出し、カルチャの名前を渡すことによって、そのカルチャを CultureInfo 表す オブジェクトをインスタンス化します。 コンストラクターは CultureInfo(String) 、 CultureInfo 新しいカルチャが現在の Windows カルチャと同じ場合に、ユーザーオーバーライドを反映する オブジェクトをインスタンス化します。 CultureInfo(String, Boolean)コンストラクターを使用すると、新しいカルチャが現在の Windows カルチャと同じ場合に、新しくインスタンス化されたCultureInfoオブジェクトがユーザーオーバーライドを反映するかどうかを指定できます。
CultureInfo.NET Core および .NET Framework 4.6 以降のバージョンの または CultureInfo.CurrentUICulture プロパティに オブジェクトCultureInfo.CurrentCultureを割り当てます。 (.NET Framework 4.5.2 以前のバージョンでは、 または Thread.CurrentUICulture プロパティに オブジェクトをThread.CurrentCulture割り当てることができます
CultureInfo
)。
次の例では、現在のカルチャを取得します。 フランス語 (フランス) のカルチャ以外の場合は、現在のカルチャがフランス語 (フランス) に変更されます。 それ以外の場合は、現在のカルチャがフランス語 (ルクセンブルク) に変更されます。
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
次の例では、現在のカルチャを取得します。 スロベニア語 (スロベニア) の他の文化である場合は、現在の文化をスロベニア語 (スロベニア) に変更します。 それ以外の場合は、現在のカルチャがクロアチア語 (クロアチア) に変更されます。
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
すべてのカルチャを取得する
メソッドを呼び出すことで、特定のカテゴリのカルチャまたはローカル コンピューターで使用できるすべてのカルチャの配列を GetCultures 取得できます。 たとえば、カスタム カルチャ、特定のカルチャ、またはニュートラル カルチャを単独または組み合わせて取得できます。
次の例では、 メソッドを GetCultures 2 回呼び出し、最初に System.Globalization.CultureTypes 列挙メンバーを使用してすべてのカスタム カルチャを取得し、次に System.Globalization.CultureTypes 列挙メンバーを使用してすべての置換カルチャを取得します。
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.
カルチャとスレッド
新しいアプリケーション スレッドが開始されると、現在のカルチャと現在の UI カルチャは、現在のスレッド カルチャではなく、現在のシステム カルチャによって定義されます。 この違いを次の例に示します。 アプリケーション スレッドの現在のカルチャと現在の UI カルチャをフランス語 (フランス) カルチャ (fr-FR) に設定します。 現在のカルチャが既に fr-FR の場合は、英語 (米国) カルチャ (en-US) に設定します。 3 つの乱数を通貨値として表示し、新しいスレッドを作成し、さらに 3 つの乱数を通貨値として表示します。 ただし、この例の出力が示すように、新しいスレッドによって表示される通貨値には、メイン アプリケーション スレッドからの出力とは異なり、フランス語 (フランス) カルチャの書式設定規則は反映されません。
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では、メイン アプリケーション スレッドが他のすべてのワーカー スレッドと同じカルチャを確実に共有する最も一般的な方法は、アプリケーション全体のカルチャの名前またはCultureInfoアプリケーション全体のカルチャを表す オブジェクトをデリゲートにSystem.Threading.ParameterizedThreadStart渡すことです。 次の例では、この方法を使用して、2 つのスレッドによって表示される通貨値に、同じカルチャの書式設定規則が反映されるようにします。
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 カルチャを同様の方法で設定できます。
.NET Framework 4.5 以降では、そのカルチャを表す オブジェクトを プロパティと プロパティに割り当てることCultureInfoで、アプリケーション ドメイン内のすべてのスレッドのカルチャと DefaultThreadCurrentUICulture UI カルチャDefaultThreadCurrentCultureをより直接設定できます。 次の例では、これらのプロパティを使用して、既定のアプリケーション ドメイン内のすべてのスレッドが同じカルチャを共有していることを確認します。
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 カルチャは、これらのプロパティ値が設定された時点で現在のアプリケーション ドメインに対してのみ定義されます。 詳細については、次のセクション「 カルチャとアプリケーション ドメイン」を参照してください。
プロパティと DefaultThreadCurrentUICulture プロパティに値をDefaultThreadCurrentCulture割り当てると、明示的にカルチャが割り当てられていない場合、アプリケーション ドメイン内のスレッドのカルチャと UI カルチャも変更されます。 ただし、これらのスレッドは、現在のアプリケーション ドメインで実行されている間にのみ、新しいカルチャ設定を反映します。 これらのスレッドが別のアプリケーション ドメインで実行される場合、そのカルチャはそのアプリケーション ドメインに対して定義されている既定のカルチャになります。 その結果、メイン アプリケーション スレッドのカルチャを常に設定し、 プロパティと DefaultThreadCurrentUICulture プロパティにDefaultThreadCurrentCulture依存して変更しないことをお勧めします。
カルチャとアプリケーション ドメイン
DefaultThreadCurrentCulture および DefaultThreadCurrentUICulture は、プロパティ値の設定または取得時に現在のアプリケーション ドメインに対してのみ既定のカルチャを明示的に定義する静的プロパティです。 次の例では、既定のアプリケーション ドメインの既定のカルチャと既定の UI カルチャをフランス語 (フランス) に設定し、 クラスと デリゲートをAppDomainInitializer使用AppDomainSetupして、新しいアプリケーション ドメインの既定のカルチャと UI カルチャをロシア語 (ロシア) に設定します。 その後、1 つのスレッドが各アプリケーション ドメインで 2 つのメソッドを実行します。 スレッドのカルチャと UI カルチャは明示的に設定されていないことに注意してください。これらは、スレッドが実行されているアプリケーション ドメインの既定のカルチャと UI カルチャから派生します。 また、 DefaultThreadCurrentCulture プロパティと DefaultThreadCurrentUICulture プロパティは、メソッド呼び出しの実行時に現在のアプリケーション ドメインの既定値 CultureInfo を返します。
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
カルチャとアプリケーション ドメインの詳細については、「アプリケーション ドメイン」トピックの「アプリケーション ドメインとスレッド」 セクションを参照 してください。
カルチャとタスクベースの非同期操作
タスク ベースの非同期プログラミング パターンでは、 オブジェクトと Task<TResult> オブジェクトを使用Taskして、スレッド プール スレッドでデリゲートを非同期に実行します。 特定のタスクが実行される特定のスレッドは、事前に認識されていませんが、実行時にのみ決定されます。
.NET Framework 4.6 以降のバージョンを対象とするアプリの場合、カルチャは非同期操作のコンテキストの一部です。 つまり、4.6 .NET Framework対象のアプリ以降では、非同期操作は既定で、起動元のスレッドの CurrentCulture プロパティと CurrentUICulture プロパティの値を継承します。 現在のカルチャまたは現在の UI カルチャがシステム カルチャと異なる場合、現在のカルチャはスレッド境界を越え、非同期操作を実行しているスレッド プール スレッドの現在のカルチャになります。
簡単な例を次に示します。 属性をTargetFrameworkAttribute使用して、.NET Framework 4.6 を対象とします。 この例では、formatDelegate
通貨値として書式設定された数値を返すデリゲート を定義Func<TResult>します。 この例では、現在のシステム カルチャをフランス語 (フランス) またはフランス語 (フランス) が既に現在のカルチャである場合は英語 (米国) に変更します。 次に、次の手順を実行します。
デリゲートを直接呼び出して、メイン アプリ スレッドで同期的に実行されるようにします。
スレッド プール スレッドでデリゲートを非同期的に実行するタスクを作成します。
メソッドを呼び出して、メイン アプリ スレッドでデリゲートを同期的に実行するタスクを Task.RunSynchronously 作成します。
この例の出力に示すように、現在のカルチャがフランス語 (フランス) に変更されると、タスクが非同期的に呼び出されるスレッドの現在のカルチャがその非同期操作の現在のカルチャになります。
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を対象とするアプリ、または特定のバージョンの.NET Frameworkを対象としていないアプリの場合、呼び出し元スレッドのカルチャはタスクのコンテキストの一部ではありません。 代わりに、明示的に定義されていない限り、既定では新しいスレッドのカルチャがシステム カルチャになります。 次の例は、 属性がない点 TargetFrameworkAttribute を除いて前の例と同じですが、これを示しています。 例が実行されたシステムのシステム カルチャは英語 (米国) であるため、スレッド プール スレッドで非同期的に実行されるタスクのカルチャは en-US
ではなく 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を対象とするアプリの場合、.NET Framework 4.6 より前のバージョンでは、 プロパティと DefaultThreadCurrentUICulture プロパティを使用DefaultThreadCurrentCultureして、呼び出し元スレッドのカルチャがスレッド プール スレッドで実行される非同期タスクで確実に使用されるようにすることができます。 次の例は、前の例と同じですが、 プロパティを DefaultThreadCurrentCulture 使用して、スレッド プールスレッドがメイン アプリ スレッドと同じカルチャを持っていることを確認します。
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 €
DefaultThreadCurrentCulture と DefaultThreadCurrentUICulture はアプリごとのドメイン プロパティです。つまり、特定のアプリケーション ドメインにカルチャが明示的に割り当てられないすべてのスレッドの既定のカルチャが確立されます。 ただし、.NET Framework 4.6 以降を対象とするアプリの場合、呼び出し元スレッドのカルチャは、タスクがアプリ ドメインの境界を越えた場合でも、非同期タスクのコンテキストの一部のままです。
次の例は、タスクが実行しているメソッドがアプリケーション ドメインの境界を超えた場合でも、呼び出し元のスレッドのカルチャがタスクベースの非同期操作の現在のカルチャのままであることを示しています。 これは、 DataRetriever
通貨値として書式設定された 1 から 1,000 までのランダムな倍精度浮動小数点数を返す 1 つのメソッド GetFormattedNumber
を使用して、 クラス を定義します。 インスタンスをインスタンス化し、そのGetFormattedNumber
メソッドを呼び出す最初のDataRetriever
タスクが実行されます。 2 番目のタスクは、現在のアプリケーション ドメインを報告し、新しいアプリケーション ドメインを作成し、新しいアプリケーション ドメインでインスタンスをインスタンス化 DataRetriever
し、そのメソッドを GetFormattedNumber
呼び出します。 例の出力に示すように、現在のカルチャは、メイン アプリケーション ドメインと 2 番目のアプリケーション ドメインで実行されていたときに、呼び出し元のスレッド、最初のタスク、2 番目のタスクで同じままです。
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 シリアル化する場合、実際に格納されるのは Name と UseUserOverrideです。 これは、同じ意味を持つ環境 Name でのみ正常に逆シリアル化されます。 次の 3 つの例は、これが必ずしも当たらない理由を示しています。
プロパティ値 CultureTypes が で CultureTypes.InstalledWin32Cultures、そのカルチャが特定のバージョンの Windows オペレーティング システムで最初に導入された場合、以前のバージョンの Windows で逆シリアル化することはできません。 たとえば、Windows 10でカルチャが導入された場合、Windows 8で逆シリアル化することはできません。
値が CultureTypesCultureTypes.UserCustomCultureで、逆シリアル化されているコンピューターにこのユーザー カスタム カルチャがインストールされていない場合、逆シリアル化することはできません。
値が CultureTypes で CultureTypes.ReplacementCultures、逆シリアル化されるコンピューターにこの置換カルチャがない場合、同じ名前に逆シリアル化されますが、すべての同じ特性は逆シリアル化されません。 たとえば、
en-US
がコンピューター A の置換カルチャであり、コンピューター B ではではなく、このカルチャを参照するオブジェクトがコンピューター A でシリアル化され、コンピューター B で逆シリアル化された場合 CultureInfo 、カルチャのカスタム特性は送信されません。 カルチャは正常に逆シリアル化されますが、意味は異なります。
コントロール パネルオーバーライド
ユーザーは、コントロール パネルの地域と言語のオプションの部分を使用して、Windows の現在のカルチャに関連付けられている値の一部をオーバーライドすることを選択できます。 たとえば、ユーザーは日付を別の形式で表示するか、カルチャの既定値以外の通貨を使用するかを選択できます。 一般に、アプリケーションでは、これらのユーザーのオーバーライドを受け入れられます。
が true
で、指定したカルチャが Windows の現在のカルチャと一致する場合UseUserOverride、 CultureInfo では、プロパティによって返されるインスタンスのDateTimeFormatInfoプロパティのユーザー設定や、 プロパティによってDateTimeFormat返されるインスタンスのNumberFormatInfoプロパティなど、これらのオーバーライドがNumberFormat使用されます。 ユーザー設定が に関連付けられている CultureInfoカルチャと互換性がない場合 (たとえば、選択した予定表が の OptionalCalendars1 つではない場合)、メソッドの結果とプロパティの値は未定義です。
代替の並べ替え順序
一部のカルチャでは、複数の並べ替え順序がサポートされています。 次に例を示します。
スペイン語 (スペイン) カルチャには、既定の国際並べ替え順序と従来の並べ替え順序の 2 つの並べ替え順序があります。 カルチャ名を使用して オブジェクトをCultureInfo
es-ES
インスタンス化すると、国際並べ替え順序が使用されます。 カルチャ名を使用して オブジェクトをCultureInfoes-ES-tradnl
インスタンス化すると、従来の並べ替え順序が使用されます。(簡体字、PRC) カルチャでは
zh-CN
、発音 (既定値) とストローク数の 2 つの並べ替え順序がサポートされています。 カルチャ名を使用して オブジェクトをCultureInfozh-CN
インスタンス化すると、既定の並べ替え順序が使用されます。 0x00020804の CultureInfo ローカル識別子を持つオブジェクトをインスタンス化すると、文字列はストローク数で並べ替えられます。
代替の並べ替え順序をサポートするカルチャと、各カルチャの既定の並べ替え順序および代替の並べ替え順序の識別子を次の表に示します。
カルチャ名 | カルチャ | 既定の並べ替え名と識別子 | 代替の並べ替え名と識別子 |
---|---|---|---|
es-ES | スペイン語 (スペイン) | International: 0x00000C0A | Traditional: 0x0000040A |
zh-TW | 中国語 (台湾) | Stroke Count: 0x00000404 | Bopomofo: 0x00030404 |
zh-CN | 中国語 (中華人民共和国) | Pronunciation: 0x00000804 | Stroke Count: 0x00020804 |
zh-HK | 中国語 (香港特別行政区) | Stroke Count: 0x00000c04 | Stroke Count: 0x00020c04 |
zh-SG | 中国語 (シンガポール) | Pronunciation: 0x00001004 | Stroke Count: 0x00021004 |
zh-MO | 中国語 (中華人民共和国マカオ特別行政区) | Pronunciation: 0x00001404 | Stroke Count: 0x00021404 |
ja-JP | 日本語 (日本) | Default: 0x00000411 | Unicode: 0x00010411 |
ko-KR | 韓国語 (韓国) | Default: 0x00000412 | Korean Xwansung - Unicode: 0x00010412 |
de-DE | ドイツ語 (ドイツ) | Dictionary: 0x00000407 | Phone Book Sort DIN: 0x00010407 |
hu-HU | ハンガリー語 (ハンガリー) | Default: 0x0000040e | Technical Sort: 0x0001040e |
ka-GE | グルジア語 (グルジア) | Traditional: 0x00000437 | Modern Sort: 0x00010437 |
現在のカルチャと UWP アプリ
ユニバーサル Windows プラットフォーム (UWP) アプリでは、 CurrentCulture プロパティと CurrentUICulture プロパティは、.NET Framework アプリと .NET Core アプリの場合と同様に、読み取り/書き込み可能です。 ただし、UWP アプリは 1 つのカルチャを認識します。 プロパティと CurrentUICulture プロパティはCurrentCulture、Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages コレクションの最初の値にマップされます。
.NET Framework アプリと .NET Core アプリでは、現在のカルチャはスレッドごとの設定でありCurrentCulture、 プロパティと CurrentUICulture プロパティには、現在のスレッドのカルチャと UI カルチャのみが反映されます。 UWP アプリでは、現在のカルチャは、グローバル設定である Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages コレクションにマップされます。 または CurrentUICulture プロパティをCurrentCulture設定すると、アプリ全体のカルチャが変更されます。カルチャはスレッドごとに設定することはできません。
コンストラクター
CultureInfo(Int32) |
カルチャ識別子によって指定するカルチャに基づいて、CultureInfo クラスの新しいインスタンスを初期化します。 |
CultureInfo(Int32, Boolean) |
カルチャ識別子で指定されたカルチャと、Windows からユーザーが選択したカルチャ設定を使用するかどうかを指定する値に基づいて、 クラスの新しいインスタンス CultureInfo を初期化します。 |
CultureInfo(String) |
名前で指定するカルチャに基づいて、CultureInfo クラスの新しいインスタンスを初期化します。 |
CultureInfo(String, Boolean) |
名前で指定されたカルチャと、Windows からユーザーが選択したカルチャ設定を使用するかどうかを指定する値に基づいて、 クラスの新しいインスタンス CultureInfo を初期化します。 |
プロパティ
Calendar |
カルチャで使用する既定の暦を取得します。 |
CompareInfo |
カルチャの文字列を比較する方法を定義する CompareInfo を取得します。 |
CultureTypes |
現在の CultureInfo オブジェクトに関するカルチャ タイプを取得します。 |
CurrentCulture |
現在のスレッドとタスク ベースの CultureInfo 非同期操作で使用されるカルチャを表す オブジェクトを取得または設定します。 |
CurrentUICulture |
実行時にカルチャ固有のリソースを参照するためにリソース マネージャーによって使用される現在のユーザー インターフェイスのカルチャを表す CultureInfo オブジェクトを取得または設定します。 |
DateTimeFormat |
カルチャに対応する、日時の表示形式を定義する DateTimeFormatInfo を取得または設定します。 |
DefaultThreadCurrentCulture |
現在のアプリケーション ドメインのスレッドの既定のカルチャを取得または設定します。 |
DefaultThreadCurrentUICulture |
現在のアプリケーション ドメイン内のスレッドの既定 UI カルチャを取得または設定します。 |
DisplayName |
完全にローカライズされたカルチャ名を取得します。 |
EnglishName |
英語で表した "languagefull [country/regionfull]" という形式のカルチャ名を取得します。 |
IetfLanguageTag |
非推奨になりました。 言語の RFC 4646 標準 ID を取得します。 |
InstalledUICulture |
オペレーティング システムと共にインストールされたカルチャを表す CultureInfo を取得します。 |
InvariantCulture |
カルチャに依存しない (インバリアントな) CultureInfo オブジェクトを取得します。 |
IsNeutralCulture |
現在の CultureInfo がニュートラル カルチャを表しているかどうかを示す値を取得します。 |
IsReadOnly |
現在の CultureInfo が読み取り専用かどうかを示す値を取得します。 |
KeyboardLayoutId |
アクティブな入力ロケール識別子を取得します。 |
LCID |
現在の CultureInfo のカルチャ識別子を取得します。 |
Name |
languagecode2-country/regioncode2 という形式のカルチャ名を取得します。 |
NativeName |
カルチャの表示設定である、言語、国/地域、およびオプションのスクリプトで構成されるカルチャ名を取得します。 |
NumberFormat |
数値、通貨、割合を表示する、カルチャに対応する書式を定義する NumberFormatInfo を取得または設定します。 |
OptionalCalendars |
カルチャで使用できる暦の一覧を取得します。 |
Parent |
現在の CultureInfo の親カルチャを表す CultureInfo を取得します。 |
TextInfo |
カルチャに関連付けられている書記体系を定義する TextInfo を取得します。 |
ThreeLetterISOLanguageName |
現在の CultureInfo の言語に対する ISO 639-2 の 3 桁の文字コードを取得します。 |
ThreeLetterWindowsLanguageName |
Windows API の定義に従って、言語に対する 3 文字コードを取得します。 |
TwoLetterISOLanguageName |
現在 CultureInfoの の言語の ISO 639-1 2 文字または ISO 639-3 3 文字コードを取得します。 |
UseUserOverride |
現在の CultureInfo オブジェクトでユーザーが選択したカルチャ設定を使用するかどうかを示す値を取得します。 |
メソッド
ClearCachedData() |
キャッシュされたカルチャ関連情報を更新します。 |
Clone() |
現在の CultureInfo のコピーを作成します。 |
CreateSpecificCulture(String) |
指定した名前に関連付けられている特定のカルチャを表す CultureInfo を作成します。 |
Equals(Object) |
指定したオブジェクトが現在の CultureInfo と同じカルチャかどうかを判断します。 |
GetConsoleFallbackUICulture() |
グラフィック ユーザー インターフェイスの既定のカルチャが不適切な場合、コンソール アプリケーションに適した代替のユーザー インターフェイス カルチャを取得します。 |
GetCultureInfo(Int32) |
指定されたカルチャ識別子を使用して、カルチャのキャッシュされた読み取り専用インスタンスを取得します。 |
GetCultureInfo(String) |
指定されたカルチャ名を使用して、カルチャのキャッシュされた読み取り専用インスタンスを取得します。 |
GetCultureInfo(String, Boolean) |
カルチャのキャッシュされた読み取り専用インスタンスを取得します。 |
GetCultureInfo(String, String) |
カルチャのキャッシュされた読み取り専用インスタンスを取得します。 パラメーターは、別のカルチャで指定された TextInfo オブジェクトおよび CompareInfo オブジェクトで初期化されたカルチャを指定します。 |
GetCultureInfoByIetfLanguageTag(String) |
非推奨になりました。 指定された RFC 4646 言語タグで示される言語特性を持つ、読み取り専用 CultureInfo オブジェクトを取得します。 |
GetCultures(CultureTypes) |
サポートされているカルチャを、指定した CultureTypes パラメーターでフィルター処理した結果のリストを取得します。 |
GetFormat(Type) |
指定した型に書式指定する方法を定義するオブジェクトを取得します。 |
GetHashCode() |
現在の CultureInfo のハッシュ関数として機能します。ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 |
GetType() |
現在のインスタンスの Type を取得します。 (継承元 Object) |
MemberwiseClone() |
現在の Object の簡易コピーを作成します。 (継承元 Object) |
ReadOnly(CultureInfo) |
指定した CultureInfo オブジェクトをラップする読み取り専用のラッパーを返します。 |
ToString() |
languagecode2-country/regioncode2 という形式で、現在の CultureInfo の名前を格納している文字列を返します。 |