我创建了简单的控制台应用程序来获取资源值。应用程序正在为现有资源键工作。但 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;
}
}
}