C# - 从程序集中获取资源字符串的最快方法
我真的不知道/没有答案,知道如何使用 c# 程序集中的 resx
文件中的键查找资源值。(或者可能是我无知)。
什么是最快的代码,我可以使用资源文件中的键检索字符串值
或值
,该资源文件作为资源嵌入集会。我在资源文件中存储异常的友好消息,并希望在需要时使用它们。
是否存在用于此目的的静态类?
有没有成熟的开源项目可供我使用?
I really don't know/have the answer, knowledge to find a resource value using a key from a resx
file in a assembly using c#.(or may be i am ignorant).
What would be the fastest code, way i can retrieve string values
or values
using a key from a resource file which is embedded as resource in a assembly. I am storing friendly messages for exceptions in the resource file and would like to use them when required.
Does a static class exist for this purpose?
Are there open source mature projects i can use for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果资源与代码位于同一程序集中,则将执行以下操作:
取自这个SO答案。
If the resource is in the same assembly as the code, then the following will do:
Taken from this SO answer.
给定“resource_name”,您可以检索资源值。
Given
"resource_name"
you can retrieve resource value.您可以使用 ResourceManger 从程序集获取字符串值
从程序集获取资源
you can use ResourceManger to get the string value from Assembly
Get Resource from Assembly
当我为 C# 类型类库的单元测试创建一个名为 UnitTests 的新项目时,我右键单击并添加了一个新资源。我将其命名为 UnitTestsResources。我向该资源添加了 2 个字符串。然后我就能够像这样方便地访问它们
UnitTestsResources.NoDeviceRequireMsg
我很好奇它是如何工作的,所以我提取了资源文件后面的代码,它是有意义的。 Visual Studio 使用静态访问器创建了一个内部类。对我来说它看起来像这样,
因为它仅用于我的单元测试,我对此感到满意。希望它对其他人有帮助。
When I made a new project for my unit tests of type C# class library called UnitTests, I right clicked and Added a new Resource. I named that UnitTestsResources. I added 2 strings to that resource. I was then able to conveniently able to access them like this
UnitTestsResources.NoDeviceRequireMsg
I was curious how that worked so i pulled up the code behind the resource file and it makes sense. Visual Studio made a internal class with static accessors.. It looks like this for me
Since it is only for my unit tests I am content with this. Hope it helps someone else.
为了改进 Herzbube 的答案,我将展示我如何实现这一点...
而不是为资源文件创建项目或文件夹,只需右键单击您的项目并执行添加 -> 即可。新项目,然后选择资源文件。打开字符串中的资源文件,另存为有用的名称,然后导航到要使用它们的 C# 位置,那么它就是:
String resourceValue = MyProjectName.MyResourceFileName.MyResourceRowItem;
如果是这样不起作用,请注意 resx 文件中的访问修饰符下拉列表。
To improve on Herzbube's answer I will show how I implemented this...
Rather than creating projects or folders for the resource file, just right click your project and do add -> new item, then choose resources file. Open the resources file stick in your strings, save as a useful name, and navigate over to C# where you want to use them, then it is just:
String resourceValue = MyProjectName.MyResourceFileName.MyResourceRowItem;
If that isnt working pay attention to the access modifier drop down when inside your resx file.