C#中对资源文件的动态引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29845/
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 08:21:32  来源:igfitidea点击:

Dynamic reference to resource files in C#

提问by Joda

I have an application on which I am implementing localization.

我有一个正在实施本地化的应用程序。

I now need to dynamically reference a name in the resouce file.

我现在需要动态引用资源文件中的名称。

assume I have a resource file called Login.resx, an a number of strings: foo="hello", bar="cruel" and baz="world"

假设我有一个名为 Login.resx 的资源文件,有一些字符串:foo="hello"、bar="cruel" 和 baz="world"

normally, I will refer as: String result =Login.foo; and result=="hello";

通常,我将引用为: String result =Login.foo; 结果==“你好”;

my problem is, that at code time, I do not know if I want to refer to foo, bar or baz - I have a string that contains either "foo", "bar" or "baz".

我的问题是,在代码时,我不知道是要引用 foo、bar 还是 baz - 我有一个包含“foo”、“bar”或“baz”的字符串。

I need something like:

我需要类似的东西:

Login["foo"];

登录["foo"];

Does anyone know if there is any way to dynamically reference a string in a resource file?

有谁知道是否有任何方法可以动态引用资源文件中的字符串?

采纳答案by Konrad Rudolph

You'll need to instance a ResourceManagerfor the Login.resx:

你需要实例ResourceManagerLogin.resx

var resman = new System.Resources.ResourceManager(
    "RootNamespace.Login",
    System.Reflection.Assembly.GetExecutingAssembly()
)
var text = resman.GetString("resname");

It might help to look at the generated code in the code-behind files of the resource files that are created by the IDE. These files basically contain readonly properties for each resource that makes a query to an internal resource manager.

查看 IDE 创建的资源文件的代码隐藏文件中生成的代码可能会有所帮助。这些文件基本上包含对内部资源管理器进行查询的每个资源的只读属性。

回答by StarCub

If you put your Resource file in the App_GlobalResources folder like I did, you need to use

如果你像我一样把你的资源文件放在 App_GlobalResources 文件夹中,你需要使用

global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RootNamespace.Login", global::System.Reflection.Assembly.Load("App_GlobalResources"));

global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RootNamespace.Login", global::System.Reflection.Assembly.Load("App_GlobalResources"));

It took me a while to figure this out. Hope this will help someone. :)

我花了一段时间才弄清楚这一点。希望这会帮助某人。:)