CultureInfo
在C#中主要用于处理与文化或区域设置相关的信息和操作。以下是一些使用CultureInfo
的用途例子:
DateTime date = DateTime.Now;
CultureInfo culture = new CultureInfo("fr-FR"); // French (France)
string formattedDate = date.ToString("D", culture); // "28/12/2023"
double number = 1234.56;
CultureInfo culture = new CultureInfo("en-US"); // English (United States)
string formattedNumber = number.ToString("C", culture); // "$1,234.56"
string str1 = "?à";
string str2 = "èé";
CultureInfo culture = new CultureInfo("fr-FR"); // French (France)
int comparisonResult = string.Compare(str1, str2, true, culture); // -1 (str1 comes before str2)
CultureInfo culture = new CultureInfo("es-ES"); // Spanish (Spain)
Console.WriteLine(culture.DisplayName); // "Spanish (Spain)"
Console.WriteLine(culture.DateTimeFormat.ShortDatePattern); // "dd/MM/yyyy"
CultureInfo userCulture = CultureInfo.InstalledUICulture;
string welcomeMessage = Resources.WelcomeMessage.ResourceManager.GetString("Welcome", userCulture);
CultureInfo invariantCulture = CultureInfo.InvariantCulture;
double value = double.Parse("1,234.56", invariantCulture); // Parses as 1234.56 regardless of the user's locale
这些例子展示了如何使用CultureInfo
来处理各种与文化或区域设置相关的问题,以确保应用程序在不同环境和背景下正确、一致地工作。