Skip to main content
 首页 » 编程设计

c#之ResourceManager 是否自动加载所有文化

2024年02月20日9三少

我有一个类库——称之为框架。在 assemblyinfo.cs 中,我有:

[assembly: NeutralResourcesLanguage("en-US")] 

在\Resources\目录下,我有 FrameworkResources.resx 和 FrameworkResources.fr-FR.resx

在辅助类中,我使用它作为我的资源管理器:

private static ResourceManager manager = new ResourceManager("Framework.Resources.FrameworkResources", Assembly.GetExecutingAssembly()); 

在代码中,如果我这样做:

String message = manager.GetString("ArgumentNullExceptionMessage", CultureInfo.CurrentCulture); 

我可以调试并将鼠标悬停在 CurrentCulture 上,它(和 UICulture)设置为 fr-FR,但这总是带回我的默认英语消息 - 而不是来自 fr-FR 资源文件的法语消息。

ResourceManager 应该自动连接它,还是我应该编写代码来查询当前的文化,然后打开正确的文件?我假设资源管理器会知道获取 fr-FR 字符串,因为那是当前的文化,我是否不正确?

我不确定为什么这不起作用。

更新: 我有附属程序集,所以相信编译部分是正常的。我认为问题出在我的资源管理器中。我尝试使用 ResourceSets 并像这样显式使用 ResourceManager:

ResourceManager manager = 
    new ResourceManager("Framework.Resources.FrameworkResources", 
        Assembly.GetExecutingAssembly()); 
 
Debug.WriteLine("de-DE : " + manager.GetString(resourceName, new CultureInfo("de-DE"))); 
Debug.WriteLine("el    : " + manager.GetString(resourceName, new CultureInfo("el"))); 
Debug.WriteLine("es-MX : " + manager.GetString(resourceName, new CultureInfo("es-MX"))); 
Debug.WriteLine("fr-FR : " + manager.GetString(resourceName, new CultureInfo("fr-FR"))); 
Debug.WriteLine("hi    : " + manager.GetString(resourceName, new CultureInfo("hi"))); 
Debug.WriteLine("zh-CN : " + manager.GetString(resourceName, new CultureInfo("zh-CN"))); 

结果是:

de-DE : Argument '%ArgumentName%' cannot be null or empty. 
el    : Argument '%ArgumentName%' cannot be null or empty. 
es-MX : Argument '%ArgumentName%' cannot be null or empty. 
fr-FR : Argument '%ArgumentName%' cannot be null or empty. 
hi    : Argument '%ArgumentName%' cannot be null or empty. 
zh-CN : Argument '%ArgumentName%' cannot be null or empty. 

因此,即使一切就绪,我的资源管理器也不会尝试查看那些附属程序集。需要明确的是,在这些程序集中,我有上面字符串的翻译版本 - 所以它肯定是从我的默认 FrameworkResources.resx 文件中读取的,而不是特定于区域性的文件。

请您参考如下方法:

我想通了(多亏了互联网上的更多搜索)。我正在运行单元测试中的代码,显然 MSTest 不会“部署”附属程序集。如果我进入测试设置并关闭“部署”,一切都会按预期进行。啊!