Uso della classe CultureInfo

La classe CultureInfo contiene informazioni specifiche dell'area geografica quali la lingua, il paese, il calendario e le convenzioni associate a una particolare lingua. Questa classe fornisce inoltre le informazioni necessarie per l'esecuzione di operazioni specifiche della lingua, come ad esempio l'uso di maiuscole/minuscole, la formattazione di date e numeri e il confronto di stringhe.

La classe CultureInfo specifica un nome univoco per ogni lingua. Per un elenco dei nomi delle lingue, vedere la descrizione della classe CultureInfo class. L'applicazione può utilizzare il metodo CultureInfo.GetCultures per recuperare un elenco completo di tutte le lingue. Nell'esempio seguente viene visualizzato un elenco di tutte le lingue.

Imports System
Imports System.Globalization

public class printClass
   Public Shared Sub Main()  
      Dim ci As CultureInfo
      For Each ci in _
      CultureInfo.GetCultures(CultureTypes.AllCultures)
         Console.WriteLine(ci)
      Next ci
   End Sub
End Class
using System;
using System.Globalization;

public class printClass
{
   public static void Main()
   {
      foreach (CultureInfo ci in
      CultureInfo.GetCultures(CultureTypes.AllCultures))
      {
         Console.WriteLine(ci);
      }
   }
}

Utilizzo di CultureInfo con codice non gestito

Le applicazioni .NET Framework possono accedere a funzioni non gestite di librerie a collegamento dinamico mediante il servizio PInvoke. Quando tuttavia l'applicazione passa un oggetto CultureInfo alla funzione Win32 GetLocaleInfo, ricordare che i dati restituiti dalla funzione non sono sempre coerenti con i dati restituiti dal costruttore della classe RegionInfo.

Un oggetto RegionInfo di .NET Framework corrisponde a un paese. Per inizializzare un oggetto RegionInfo mediante un oggetto CultureInfo, è necessario indicare un oggetto CultureInfo che rappresenti una lingua specifica, ad esempio ar-DZ per la lingua araba dell'Algeria. Se si tenta di inizializzare un oggetto RegionInfo con un oggetto CultureInfo che rappresenta una lingua non associata ad alcun paese, ad esempio "ar" per la lingua araba, verrà generata un'eccezione. La lingua non associata ad alcun paese non specifica le informazioni necessarie per eseguire il mapping a un paese.

La funzione GetLocaleInfo dell'API differisce dal costruttore di RegionInfo poiché restituisce un paese per un oggetto CultureInfo, indipendentemente dal fatto che rappresenti una lingua specifica o una lingua non associata ad alcun paese. Se ad esempio l'applicazione passa un oggetto CultureInfo che rappresenta la lingua non associata ad alcun paese "ar" (arabo) a GetLocaleInfo, la funzione esegue il mapping della lingua al paese predefinito a cui è associata. In questo caso, GetLocaleInfo restituisce Arabia Saudita. Quando si utilizza la funzione GetLocaleInfo, è necessario prestare attenzione poiché il mapping predefinito del paese potrebbe non essere appropriato per l'applicazione. Per eliminare questa discrepanza, in caso di interazione con una funzione di un'API, fare in modo che l'applicazione utilizzi solo lingue specifiche.

Nell'esempio seguente viene dimostrato come il costruttore della classe RegionInfo e la funzione GetLocaleInfo possono restituire valori diversi quando viene passato lo stesso oggetto CultureInfo. Quando l'oggetto CultureInfo rappresenta la lingua specifica ar-DZ per l'arabo (Algeria), il nome di paese restituito da entrambi i metodi è Algeria. I risultati differiscono invece quando l'oggetto CultureInfo rappresenta la lingua non associata ad alcun paese ar (arabo). Il costruttore di RegionInfo non restituisce alcun paese, mentre GetLocaleInfo restituisce Algeria.

Imports System
Imports System.Globalization
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic

Namespace CountryRegionName
   Class CountryRegionName
      ' The name of a country or region in English.
      Private LOCALE_SENGCOUNTRY As Integer = &H1002

      ' Use COM interop to call the Win32 API GetLocalInfo.
      Declare Unicode Function GetLocaleInfoW Lib "Kernel32.dll" _
         (Locale As Integer, LCType As Integer,<[In](), _
          MarshalAs(UnmanagedType.LPWStr)> lpLCData As String, _
          cchData As Integer) As Integer
      
      ' A method to retrieve the .NET Framework Country/Region
      ' that maps to the specified CultureInfo.
      Public Function GetNetCountryRegionName(ci As CultureInfo) As String
         ' If the specified CultureInfo represents a specific culture,
         ' the attempt to create a RegionInfo succeeds.
         Try
            Dim ri As New RegionInfo(ci.LCID)
            Return ri.EnglishName
         ' Otherwise, the specified CultureInfo represents a neutral
         'culture, and the attempt to create a RegionInfo fails.
         Catch
            Return String.Empty
         End Try
      End Function
      
      ' A method to retrieve the Win32 API Country/Region
      ' that maps to the specified CultureInfo.
      Public Function GetWinCountryRegionName(ci As CultureInfo) As String
         Dim size As Integer = GetLocaleInfoW(ci.LCID, _
            LOCALE_SENGCOUNTRY, Nothing, 0)
         Dim str As New String(" "c, size)
         Dim err As Integer = GetLocaleInfoW(ci.LCID, _
            LOCALE_SENGCOUNTRY, str, size)
         ' If the string is not empty, GetLocaleInfoW succeeded.
         ' It will succeed regardless of whether ci represents
         ' a neutral or specific culture.
         If err <> 0 Then
            Return str
         Else
            Return String.Empty
         End If
      End Function

      <STAThread()> _
      Public Shared Sub Main(args() As String)
         Dim crn As New CountryRegionName()
         
         ' Create a CultureInfo initialized to the neutral Arabic culture.
         Dim ci1 As New CultureInfo(&H1)
         Console.WriteLine(ControlChars.NewLine + _
            "The .NET Region name: {0}", _
            crn.GetNetCountryRegionName(ci1))
         Console.WriteLine("The Win32 Region name: {0}", _
            crn.GetWinCountryRegionName(ci1))
         
         ' Create a CultureInfo initialized to the specific 
         ' culture Arabic in Algeria.
         Dim ci2 As New CultureInfo(&H1401)
         Console.WriteLine(ControlChars.NewLine + _
            "The .NET Region name: {0}", _
            crn.GetNetCountryRegionName(ci2))
         Console.WriteLine("The Win32 Region name: {0}", _
            crn.GetWinCountryRegionName(ci2))
      End Sub
   End Class
End Namespace
using System;
using System.Globalization;
using System.Runtime.InteropServices;

namespace CountryRegionName
{
  class CountryRegionName
  {
    // The name of a country or region in English
    int LOCALE_SENGCOUNTRY     = 0x1002;

    // Use COM interop to call the Win32 API GetLocalInfo.
    [DllImport("kernel32.dll", CharSet=CharSet.Unicode)]
    public static extern int GetLocaleInfo(
       // The locale identifier.
       int Locale,
       // The information type.
       int LCType,
       // The buffer size.
       [In, MarshalAs(UnmanagedType.LPWStr)] string lpLCData,int cchData
     );

    // A method to retrieve the .NET Framework Country/Region
    // that maps to the specified CultureInfo.
    public String GetNetCountryRegionName(CultureInfo ci)
    {
      // If the specified CultureInfo represents a specific culture,
      // the attempt to create a RegionInfo succeeds.
      try
      {
        RegionInfo ri = new RegionInfo(ci.LCID);
        return ri.EnglishName;
      }
      // Otherwise, the specified CultureInfo represents a neutral
      // culture, and the attempt to create a RegionInfo fails.
      catch
      {
        return String.Empty;
      }
    }

    // A method to retrieve the Win32 API Country/Region
    // that maps to the specified CultureInfo.
    public String GetWinCountryRegionName(CultureInfo ci)
    {
      int size = GetLocaleInfo(ci.LCID, LOCALE_SENGCOUNTRY, null, 0);
      String str = new String(' ', size);
      int err  = GetLocaleInfo(ci.LCID, LOCALE_SENGCOUNTRY, str, size);
      // If the string is not empty, GetLocaleInfo succeeded.
      // It will succeed regardless of whether ci represents
      // a neutral or specific culture.
      if(err != 0)  
        return str;
      else
        return String.Empty;
    }

    [STAThread]
    static void Main(string[] args)
    {
      CountryRegionName crn = new CountryRegionName();

      // Create a CultureInfo initialized to the neutral Arabic culture.
      CultureInfo ci1 = new CultureInfo(0x1);  
      Console.WriteLine("\nThe .NET Region name: {0}", 
         crn.GetNetCountryRegionName(ci1));
      Console.WriteLine("The Win32 Region name: {0}",
         crn.GetWinCountryRegionName(ci1));

      // Create a CultureInfo initialized to the specific 
      // culture Arabic in Algeria.
      CultureInfo ci2 = new CultureInfo(0x1401);  
      Console.WriteLine("\nThe .NET Region name: {0}", 
         crn.GetNetCountryRegionName(ci2));
      Console.WriteLine("The Win32 Region name: 
         {0}",crn.GetWinCountryRegionName(ci2));
    }
   }
}

Questo esempio produce il seguente output:

The .NET Region name:
The Win32 Region name: Saudi Arabia

The .NET Region name: Algeria
The Win32 Region name: Algeria

Vedere anche

Riferimenti

CultureInfo Class

Concetti

Uso della proprietà CurrentUICulture
Uso della proprietà CurrentCulture
Uso della proprietà InvariantCulture
Nomi associati a un oggetto CultureInfo

Altre risorse

Codifica e localizzazione