【问题标题】:Is it better to access directly resource.resx instead of ResourceManager?直接访问resource.resx而不是ResourceManager更好吗?
【发布时间】:2016-09-23 04:12:06
【问题描述】:

我知道两种从资源文件中获取字符串的方法。

方法一:直接访问。

string str = _NAMESPACE.Properties.Resources.HelloWorld;

方法2:通过ResourceManager。

ResourceManager rm = new ResourceManager("_NAMESPACE.Properties.Resources", Assembly.GetExecutingAssembly());
string str = rm.GetString("HelloWorld");

如果有多个本地化资源文件,这两种方法都会得到正确的本地化字符串。

如果我在字符串键中输入错误,method1 将在构建时失败。 Method2 将失败,直到运行时。因此,我认为method1优于method2。

我在这个论坛上发现了一些类似的问题。但是,我的问题仍然没有得到很好的答案。

  1. Why is it better to call the ResourceManager class as opposed to loading resources directly by name?

  2. Need to use ResourceManager + GetString to support cultures OR I can just point directly at the resource file?

方法1真的更好吗?

【问题讨论】:

  • 看看第二个代码中所有那些硬编码的字符串!第一个对重构更友好。
  • 如果您希望将资源分配到 多个 资源文件(例如,Properties.MessagesProperties.Icons 等),请参阅this question 及其答案。

标签: c# localization


【解决方案1】:

我相信第一种方法更好,因为当您使用第二种方法时,您正在创建资源管理器的新实例,我认为这是对内存的不必要使用。

编辑*

阅读本文后: https://msdn.microsoft.com/en-us/library/7k989cfy(v=vs.90).aspx

看起来基本一样,直接用resources类访问资源的时候,内部是用resource manager类来创建对象的实例的。

【讨论】:

  • 您绝对正确,两者都使用 ResourceManager 类,但这并不能否定您在 sn-p 2 中创建新实例的观点。第一个版本创建一个实例并重用它根据需要多次。
  • @BenVoigt 啊,谢谢您的确认,这是我最初的思路,经过认真思考后我开始怀疑自己。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多