两个ResourceManagers使用一个作为另一个的后备

时间:2016-06-30 13:51:06

标签: c# resx

鉴于我有两个resourceManagers:

var mgr1 = new ResourceManager("NS1.StringResources", Assembly.GetExecutingAssembly());
var mgr2 = new ResourceManager("NS2.OtherStringResources", _otherAssembly);

有没有办法可以合并它们?或者他们的资源集。这样我就可以拥有一个经理或资源集。

2 个答案:

答案 0 :(得分:1)

不是很漂亮,但最终会出现在Merged词典中:

var mgr1 = new ResourceManager("NS1.StringResources", Assembly.GetExecutingAssembly());
      var mgr2 = new ResourceManager("NS2.OtherStringResources", _otherAssembly);
      var combined = new Dictionary<string, object>();
      ResourceSet resourceSet = mgr1.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
      foreach (DictionaryEntry entry in resourceSet) {
        string resourceKey = entry.Key.ToString();
        object resource = entry.Value;
        combined.Add(resourceKey, resource);
      }
      resourceSet = mgr2.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
      foreach (DictionaryEntry entry in resourceSet) {
        string resourceKey = entry.Key.ToString();
        object resource = entry.Value;
        combined.Add(resourceKey, resource);
      }

答案 1 :(得分:1)

结束类似的东西,似乎字典是唯一的出路。

public Dictionary<string, string> GetTotalResourceSet(CultureInfo culture)
    {
        Dictionary<string, string> set;
        if (_resources.TryGetValue(culture.Name, out set))
            return set;

        var wl = getWhitelabelResourceSet(culture);
        var loc = getLocalResourceSet(culture);

        var dict = loc.Cast<DictionaryEntry>()
           .ToDictionary(x => { return x.Key.ToString(); }, x =>
           {
               if (x.Value.GetType() == typeof(string))
                   return x.Value.ToString();
               return "";
           });

        if (wl != null)
        {
            var wlDict = wl.Cast<DictionaryEntry>()
               .ToDictionary(x => { return x.Key.ToString(); }, x =>
               {
                   if (x.Value.GetType() == typeof(string))
                       return x.Value.ToString();
                   return "";
               });
            set = wlDict.Concat(dict.Where(kvp => !wlDict.ContainsKey(kvp.Key))).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        }
        else
        {
            set = dict;
        }


        if (set != null)
        {
            _resources.TryAdd(culture.Name, set);
        }
        return set;
    }