我的应用程序中有以下设置:
MyResources.resx // english strings
MyResources.zh-CN.resx // chinese strings
由于翻译过程滞后,某些键具有英文值但没有中文值。在其他情况下,整个zh-CN resx文件不存在。默认情况下,如果中文值不存在,ResourceManager
将回退到英文值。在大多数情况下,这对我的用例来说是可以接受的。但是,我目前需要获取中文资源字符串而不回退到英文。
我的问题是:做这件事的正确方法是什么?
我最初认为这可以通过GetResourceSet方法完成:
var manager = MyResources.ResourceManager;
var set = manager.GetResourceSet(CultureInfo.GetCultureInfo("zh-CN"), createIfNotExists: true, tryParents: false);
if (set == null || set.GetString("key") == null) { /* not translated! */ }
// however, this has issues because resource set lookup is cached:
// this will force the association of the zh-CN culture with the
// English resource set unde the hood
manager.GetString("key", CultureInfo.GetCultureInfo("zh-CN"));
// now this returns the English resource set, thus breaking my check
var set2 = manager.GetResourceSet(CultureInfo.GetCultureInfo("zh-CN"), createIfNotExists: true, tryParents: false);
if (set == null || set.GetString("key") == null) { /* checks whether key exists in english :-( */ }
答案 0 :(得分:1)
这是一次性场景,因为意图始终是提供后备。但你仍然可以解决它,像这样(稍微简单的例子)。这仅返回ResourceManager
为其特定文化提供的内容,如果它与默认文化不同。
我只是根据习惯/惯例在构造函数中添加了一些东西。您可以将ResourceManager
,所需的CultureInfo
或两者移动到方法参数。
public class NonFallbackResourceManager
{
private readonly CultureInfo _desiredCulture;
private readonly ResourceManager _resourceManager;
public NonFallbackResourceManager(CultureInfo desiredCulture, ResourceManager resourceManager)
{
_desiredCulture = desiredCulture;
_resourceManager = resourceManager;
}
public string GetString(string key)
{
var desiredCultureString = _resourceManager.GetString(key, _desiredCulture);
var defaultCultureString = _resourceManager.GetString(key, CultureInfo.InvariantCulture);
return string.Equals(desiredCultureString, defaultCultureString)
? String.Empty
: desiredCultureString;
}
}
它没有考虑可能存在多个回退级别的情况。