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

Bar*_*chs 30 c# resources

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

using MyNamespace.Resources

...

string someString = strings.someString;
Run Code Online (Sandbox Code Playgroud)

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

string someString = GetString("someString");
Run Code Online (Sandbox Code Playgroud)

我一直在玩弄它ResourceManager,但我找不到办法将它指向我的strings.resx档案.

我怎么做?

Bar*_*chs 48

有点搜索就可以了.ResourceManagerstrings班上有权利:

ResourceManager rm = strings.ResourceManager;
string someString = rm.GetString("someString");
Run Code Online (Sandbox Code Playgroud)


Vla*_*lad 22

ResourceManager.GetString 应该做.

从MSDN中删除示例:

ResourceManager rm = new ResourceManager("RootResourceName",
                                         typeof(SomeClass).Assembly);
string someString = rm.GetString("someString");
Run Code Online (Sandbox Code Playgroud)

  • 是的,但我不知道``RootResourceName``或`SomeClass`应该是什么.`strings.ResourceManager`更容易. (2认同)
  • @Bart:只有在进入程序集时才需要类.你也许可以只使用`Assembly.GetCurrentAssembly`或类似的东西.根据文档,`RootResourceName`是"没有扩展名但包含任何完全限定名称空间名称的资源文件的根名称.例如,名为MyApplication.MyResource.en-US.resources的资源文件的根名称是MyApplication.MyResource." 但是,如果资源管理器已经可用,最好按原样使用它. (2认同)

ska*_*let 11

我使用ASP.NET Core MVC遇到了同样的问题并设法使用它来解决它

ResourceManager rm = new ResourceManager(typeof(YourResourceClass));
string someString = rm.GetString("someString");
Run Code Online (Sandbox Code Playgroud)

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


bat*_*aci 8

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

 [NameOfyourResxfile].ResourceManager.GetString("String Name");
Run Code Online (Sandbox Code Playgroud)

在你的情况下

strings.resx.ResourceManager.GetString("someString");
Run Code Online (Sandbox Code Playgroud)


A.D*_*ara 5

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

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

并在任何地方调用:

var title=  GetResourceTitle<*YouResourceClass*>(key);
Run Code Online (Sandbox Code Playgroud)

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