1
我正在創建一個將enum轉換爲友好字符串的方法。友好名稱存儲在資源文件中並受全球化影響。所以我創建了兩個資源文件:Enums.resx和Enums.pt-BR.resx,其中的鍵是枚舉的名稱,後面跟着它的值(即DeliveryStatus_WaitingForPayment)。動態加載資源並讀取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"))
{
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。
我在做什麼錯?