C# 从字符串资源动态获取字符串

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

Getting a string dynamically from strings resources

c#resources

提问by Bart Friederichs

I am working on a localised C#.NET application and we are using a strings.resxfile to translate hardcoded strings in the application. I use the following code to extract them:

我正在开发一个本地化的 C#.NET 应用程序,我们正在使用一个strings.resx文件来翻译应用程序中的硬编码字符串。我使用以下代码来提取它们:

using MyNamespace.Resources

...

string someString = strings.someString;

But, now I want to be able to define the name of the string in the call, something like this:

但是,现在我希望能够在调用中定义字符串的名称,如下所示:

string someString = GetString("someString");

I have been toying a little with the ResourceManager, but i can't find a way to direct it to my strings.resxfile.

我一直在玩弄ResourceManager,但我找不到将它定向到我的strings.resx文件的方法。

How do I do that?

我怎么做?

采纳答案by Bart Friederichs

A little searching did the trick. I have the right ResourceManageravailable in my stringsclass:

稍微搜索一下就行了。我有权利ResourceManager可以在我的strings类:

ResourceManager rm = strings.ResourceManager;
string someString = rm.GetString("someString");

回答by Vlad

ResourceManager.GetStringshould do.

ResourceManager.GetString应该做。

Stripped down example from MSDN:

来自 MSDN 的精简示例:

ResourceManager rm = new ResourceManager("RootResourceName",
                                         typeof(SomeClass).Assembly);
string someString = rm.GetString("someString");

回答by skamlet

I had the same problem using ASP.NET Core MVC and managed to solve it using

我在使用 ASP.NET Core MVC 时遇到了同样的问题,并设法使用

ResourceManager rm = new ResourceManager(typeof(YourResourceClass));
string someString = rm.GetString("someString");

Very similar to @Vlad's solution, but otherwise I had a MissingManifestResourceException

与@Vlad 的解决方案非常相似,但除此之外我有一个 MissingManifestResourceException

回答by A.Dara

You can write a static method like this:

您可以编写这样的静态方法:

public static string GetResourceTitle<T>(string key)
{
  ResourceManager rm = new ResourceManager(typeof(T));
  string someString = rm.GetString(key);
  return someString;
}

And call anywhere:

并在任何地方调用:

var title=  GetResourceTitle<*YouResourceClass*>(key);

It is useful when you want to have a generic function to get String of any Resource file.

当您想要一个通用函数来获取任何资源文件的字符串时,它很有用。

回答by batmaci

There is much simpler way of doing this

有更简单的方法可以做到这一点

 [NameOfyourResxfile].ResourceManager.GetString("String Name");

in your case

在你的情况下

strings.resx.ResourceManager.GetString("someString");