我正在创建一个将枚举转换为友好字符串的方法。友好名称存储在资源文件中,并受全球化的影响。所以我创建了两个资源文件:Enums.resx和Enums.pt-BR.resx,其密钥是枚举的名称,后跟它的值(即DeliveryStatus_WaitingForPayment)。
这是我用来加载资源并获取枚举的相应友好名称的代码:
public static string EnumToString<T>(object obj)
{
string key = String.Empty;
Type type = typeof(T);
key += type.Name + "_" + obj.ToString();
Assembly assembly = Assembly.Load("EnumResources");
string[] resourceNames = assembly.GetManifestResourceNames();
ResourceManager = null;
for(int i = 0; i < resourceNames.Length; i++)
{
if(resourceNames[i].Contains("Enums.resources"))
{
rm = new ResourceManager(resourceNames[i], Assembly.GetExecutingAssembly());
Stream resStream = assembly.GetManifestResourceStream(resourceNames[i]);
ResourceReader reader = new ResourceReader(resStream);
IDictionaryEnumerator dict = reader.GetEnumerator();
while (dict.MoveNext())
{
string keyToCompare = dict.Key.ToString();
if (keyToCompare == key)
return dict.Value.ToString();
}
}
return obj.ToString();
}
}
除了忽略CurrentUICulture并且总是从默认资源返回值之外,这个方法几乎完美无缺,也就是说,即使我使用pt-BR作为我的CurrentUICulture,它也会从Enum.resx中加载值而不是Enum.pt-BR.resx。
我做错了什么?
答案 0 :(得分:1)
事实证明我采用了错误的方法来读取资源文件。不仅我不需要在流中工作,它阻止我根据CurrentUICulture获得结果。
解决方案比我第一次尝试的解决方案容易得多:
public static string EnumToString<T>(object obj)
{
string key = String.Empty;
Type type = typeof(T);
key += type.Name + "_" + obj.ToString();
Assembly assembly = Assembly.Load("EnumResources");
string[] resourceNames = assembly.GetManifestResourceNames();
ResourceManager = null;
for(int i = 0; i < resourceNames.Length; i++)
{
if(resourceNames[i].Contains("Enums.resources"))
{
//The substring is necessary cause the ResourceManager is already expecting the '.resurces'
rm = new ResourceManager(resourceNames[i].Substring(0, resourceNames[i].Length - 10), assembly);
return rm.GetString(key);
}
return obj.ToString();
}
}
我希望这有助于任何人在将来尝试类似的东西!