C# 确定资源管理器中是否存在资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/160022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:11:20  来源:igfitidea点击:

Determine if a resource exists in ResourceManager

提问by Kris Erickson

Is there anyway to determine if a ResourceManager contains a named resource? Currently I am catching the MissingManifestResourceException but I hate having to use Exceptions for non-exceptional situations. There must be some way to enumerate the name value pairs of a ResourceManager through reflection, or something?

无论如何确定 ResourceManager 是否包含命名资源?目前我正在捕获 MissingManifestResourceException,但我讨厌在非异常情况下使用 Exceptions。一定有什么办法可以通过反射来枚举一个ResourceManager的名字值对,或者其他什么?

EDIT: A little more detail. The resources are not in executing assembly, however the ResourceManager is working just fine. If I try _resourceMan.GetResourceSet(_defaultCuture, false, true)I get null, whereas if I try _resourceMan.GetString("StringExists")I get a string back.

编辑:更详细一点。资源不在执行程序集中,但是 ResourceManager 工作正常。如果我尝试_resourceMan.GetResourceSet(_defaultCuture, false, true)我得到空值,而如果我尝试_resourceMan.GetString("StringExists")我得到一个字符串。

采纳答案by Jonathan C Dickinson

You can use the ResourceSet to do that, only it loads all the data into memory if you enumerate it. Here y'go:

您可以使用 ResourceSet 来做到这一点,如果您枚举它,它只会将所有数据加载到内存中。给你:

    // At startup.
    ResourceManager mgr = Resources.ResourceManager;
    List<string> keys = new List<string>();

    ResourceSet set = mgr.GetResourceSet(CultureInfo.CurrentCulture, true, true);
    foreach (DictionaryEntry o in set)
    {
        keys.Add((string)o.Key);
    }
    mgr.ReleaseAllResources();

    Console.WriteLine(Resources.A);

回答by user7116

I think you can use something like Assembly.GetManifestResourceNamesto enumerate the list of resources available in the Assembly's manifest. It isn't pretty and doesn't solve all of the corner cases, but works if required.

我认为您可以使用诸如Assembly.GetManifestResourceNames 之类的东西来枚举程序集清单中可用的资源列表。它并不漂亮,也不能解决所有的极端情况,但如果需要可以工作。