我们的应用程序中有几千个本地化字符串。我想创建一个单元测试来遍历所有键和我们支持的所有语言,以确保每种语言都有默认(英语)resx文件中的每个键。
我的想法是使用反射从Strings类获取所有键,然后使用ResourceManager比较每种语言中每个键的检索值,并进行比较,以确保它与英语版本不匹配,但当然,有些词在多种语言中是相同的。
是否有方法检查ResourceManager是否从附属程序集获取值,而不是从默认资源文件获取值?
示例调用:

string en = resourceManager.GetString("MyString", new CultureInfo("en"));
string es = resourceManager.GetString("MyString", new CultureInfo("es"));

//compare here

最佳答案

调用ResourceManager.GetResourceSet方法获取中性和本地化区域性的所有资源,然后比较两个集合:

ResourceManager resourceManager = new ResourceManager(typeof(Strings));
IEnumerable<string> neutralResourceNames = resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, false)
    .Cast<DictionaryEntry>().Select(entry => (string)entry.Key);
IEnumerable<string> localizedResourceNames = resourceManager.GetResourceSet(new CultureInfo("es"), true, false)
    .Cast<DictionaryEntry>().Select(entry => (string)entry.Key);

Console.WriteLine("Missing localized resources:");
foreach (string name in neutralResourceNames.Except(localizedResourceNames))
{
    Console.WriteLine(name);
}

Console.WriteLine("Extra localized resources:");
foreach (string name in localizedResourceNames.Except(neutralResourceNames))
{
    Console.WriteLine(name);
}

07-26 09:32
查看更多