2010-06-26 47 views
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。

我在做什麼錯?

回答

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(); 
     } 

} 

我希望這可以幫助任何人試圖在未來類似的東西!