获得用户文化,而不是线程文化 [英] Get user culture, not thread culture
问题描述
当我的应用程序启动时,它将自己的区域性设置为 CultureInfo.InvariantCulture
,但是在某些地方,我想根据用户在Windows中设置的内容使用本地化的数字格式.我怎样才能做到这一点? System.Globalization.CultureInfo.CurrentCulture
仅返回线程的区域性,该区域性不再是用户的默认值.
When my application starts, it sets its own culture to CultureInfo.InvariantCulture
but in some places, I want to use localized number formatting according to what the user has set in Windows. How can I do this?
System.Globalization.CultureInfo.CurrentCulture
only returns the thread's culture which is no longer the user's default.
我希望找到一种比存储线程的默认区域性更优雅的方法,然后再更改或创建新线程以从中读取区域性.
I'm hoping for a more elegant way than storing the thread's default culture before changing it or creating a new thread just to read the culture out of it.
也许Windows功能 GetUserDefaultLocaleName
有内置的.Net包装器?
Maybe there's a built-in .Net wrapper for the Windows function GetUserDefaultLocaleName
?
推荐答案
System.Globalization.CultureInfo
具有名为
System.Globalization.CultureInfo
has an internal property named UserDefaultCulture
which is the equivalence of the Win32 GetUserDefaultLCID()
as commented in .NET Source code:
//
// This is the equivalence of the Win32 GetUserDefaultLCID()
//
internal static CultureInfo UserDefaultCulture
因此,您可以使用它以这种方式获取用户默认区域性:
So you can use it to get user default culture this way:
var property = typeof(System.Globalization.CultureInfo).GetProperty("UserDefaultCulture",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
var culture = (System.Globalization.CultureInfo)property.GetValue(null);
作为另一个选项,您可以创建一个新线程并使用其 CurrentCulture
属性:
Also as another option, you can create a new thread and use its CurrentCulture
property:
var culture = new System.Threading.Thread(() => { }).CurrentCulture;
这篇关于获得用户文化,而不是线程文化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!