1

我创建了简单的控制台应用程序来获取资源值。应用程序正在为现有资源键工作。但 MissingManifestResourceException 会因不存在的资源键而引发。请问我的代码有什么问题?资源文件的构建操作设置为嵌入式资源。

程序.cs

using Framework;

namespace ResourcesConsole
{
  class Program
  {
    static void Main(string[] args)
    {
      string resourceValue = CustomResourceManager.GetResourceValue("notExistingResourceKey");
    }
  }
}

自定义资源管理器.cs

using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Resources;

namespace Framework
{
  public class CustomResourceManager
  {
    private static Dictionary<string, ResourceManager> _resourceManagerDict;

    static CustomResourceManager()
    {
      _resourceManagerDict = new Dictionary<string, ResourceManager>();

      string defaultResourceManagerName = "Framework.CustomResources";
      ResourceManager defaultResourceManager = new System.Resources.ResourceManager(defaultResourceManagerName, Assembly.GetExecutingAssembly());

      _resourceManagerDict.Add(defaultResourceManagerName, defaultResourceManager);
    }

    public static string GetResourceValue(string key, string language = "en")
    {
      CultureInfo culture = new CultureInfo(language);

      string value = null;

      foreach (var resourceManager in _resourceManagerDict)
      {
        value = resourceManager.Value.GetString(key, culture); // MissingManifestResourceException is thrown when resource key is not found in resource file (should return null)

        if (value != null)
          return value;
      }

      return key;
    }
  }
}

解决方案

4

1 回答 1

1

我找到了解决方案。问题是我缺少不变(或默认)文化的资源文件。所以我将CustomeResources.en.resx重命名为CustomeResources.resx,它工作正常

于 2014-01-30T05:17:40.087 回答