【问题标题】:Dynamically loading a resource and reading the correct value for the CurrentUICulture动态加载资源并读取 CurrentUICulture 的正确值
【发布时间】:2010-06-26 18:59:58
【问题描述】:

我正在创建一种将枚举转换为友好字符串的方法。友好名称存储在资源文件中并受制于全球化。所以我创建了两个资源文件: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 加载值而不是枚举.pt-BR.resx。

我做错了什么?

【问题讨论】:

    标签: c# resources globalization resx resourcemanager


    【解决方案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();
          }
    
    }
    

    我希望这对以后尝试类似事情的人有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      • 2011-01-16
      相关资源
      最近更新 更多