我有几个资源文件,例如
default.aspx.resx,default.aspx.nl.resx,default.aspx.en.resx
现在,当我在荷兰语域时,会加载default.aspx.nl.resx。 但现在我想从default.aspx.en.resx访问该值并获取属于名称“title”的英文值。
我现在可以通过更改当前文化服务器端来实现此目的,访问该值然后将其更改回来,如下所示:
Dim culture As CultureInfo = New CultureInfo("en")
Threading.Thread.CurrentThread.CurrentCulture = culture
Threading.Thread.CurrentThread.CurrentUICulture = culture
Dim title as String = GetLocalResourceObject("title")
culture = New CultureInfo("nl")
Threading.Thread.CurrentThread.CurrentCulture = culture
Threading.Thread.CurrentThread.CurrentUICulture = culture
但是有更好/更快的方式吗?最好不必更改当前线程的文化,所以我可以定义我想要访问哪个资源文件以及使用哪种语言?
答案 0 :(得分:3)
您可以添加参数您的目标文化
GetLocalResourceObject("title","YourCulture");
答案 1 :(得分:2)
编辑:(抱歉,我不知道你想要另一种与此不同的方法,但这是我设法做到的唯一方法:)
我设法做到了这一点:
var userLanguage = "en-US";
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(userLanguage);
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(userLanguage);
HttpContext.GetGlobalResourceObject("MyAppResource", "KeyThatIWantToGet");
MyAppResource的位置是.resx文件的命名方式,KeyThatIWantToGet解释了自己。
答案 2 :(得分:0)
当不使用HttpContext(通用.NET应用程序)时,我使用以下帮助程序:
/// <summary>
/// Disposable class that lets us assume a specific culture while executing
/// a certain block of code. You'd typically use it like this:
///
/// using (new CultureContext("de"))
/// {
/// // Will return the German translation of "Please click here"
/// string text = SharedResource.Please_click_here;
/// }
/// </summary>
public class CultureContext : IDisposable
{
private readonly CultureInfo _previousCulture;
private readonly CultureInfo _previousUiCulture;
public CultureContext(CultureInfo culture)
{
// Save off the previous culture (we'll restore this on disposal)
_previousCulture = Thread.CurrentThread.CurrentCulture;
_previousUiCulture = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
public CultureContext(string cultureCode)
: this(new CultureInfo(cultureCode))
{
}
/// <summary>
/// Syntactic sugar so that we can switch to a culture context as follows:
///
/// using (CultureContext.For("de"))
/// {
/// // Will return the German translation of "Please click here"
/// string text = SharedResource.Please_click_here;
/// }
/// </summary>
public static CultureContext For(string cultureCode)
{
return new CultureContext(cultureCode);
}
public void Dispose()
{
// Restore the culture settings that were in place before switching
// to this context
Thread.CurrentThread.CurrentCulture = _previousCulture;
Thread.CurrentThread.CurrentUICulture = _previousUiCulture;
}
}