如何避免硬编码字符串
这是一个关于最佳编码实践的问题。 我想知道关于如何最好地避免在 .NET 应用程序中对字符串和值进行硬编码的共识。 到目前为止,我在以前工作过的地方所看到的:
- 使用资源 .resx 文件
- 将这些值和字符串存储在 App.config 或 web.config 中
创建一个静态类 ApplicationStrings 并在其中声明所有字符串和值:< /p>
公共静态类ApplicationStrings { #区域常量 公共常量字符串APPLICATION_NAME =“X”; 公共常量字符串APPLICATION_RESOURCEMANAGER_NAME =“ResourceManagerX”; 公共常量字符串APPLICATION_DEFAULT_LOGFILENAME =“log.txt”; }
但是,不是第三种方法,只是另一种硬编码吗?开设这样的课程有意义吗?这样做的好处是所有字符串都位于一个位置,但这真的可以避免硬编码吗?
另外,如果您针对这种情况养成了其他习惯,请随时发帖。
This is a question regarding best coding practices.
I would like to know the consensus about how to best avoid hardcoding strings and values in a .NET application.
What I've seen so far where I have previously worked:
- using resource .resx files
- storing these values and strings in App.config or web.config
making a static class ApplicationStrings and declaring all the strings and values in there:
public static class ApplicationStrings { #region constants public const string APPLICATION_NAME = "X"; public const string APPLICATION_RESOURCEMANAGER_NAME = "ResourceManagerX"; public const string APPLICATION_DEFAULT_LOGFILENAME = "log.txt"; }
However, is not the 3rd method, just another hardcode? Does it make sense to have such a class? The benefit would be that all strings are in one place, but is that really avoiding a hardcode?
Also, if you have developed other habits for this situation, feel free to post.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
主要好处确实是将所有字符串放在一个地方,您只需在那里更改它即可更新整个程序。如果程序的不同部分使用相同的字符串,并且一个实例得到更新,但另一个实例没有更新,那么就会遇到问题。顺便说一句,这对于所有文字都适用。
然后,对于资源文件,就有 i18n 和 l10n 的好处。如果您需要它,但许多大型应用程序都应该这样做。
The main benefit is indeed to have all strings in one place and you only need to change it there to update the whole program. If different parts of your program use the same string and one instance gets updated, but another not, then you have a problem. This holds true for all literals, by the way.
And then with resource files there is the benefit of i18n and l10n. If you need it, but many large applications should.
一般来说,我认为将所有可配置数据存储在中央配置文件中是一种很好的做法,这样所有数据都位于一个位置并且可以由其他应用程序共享
in general i believe it is good practice to store all configurable data in a central config file so all the data is in one place and can be shared by other apps
在我看来,只有当您的设置(i)真正恒定并且(ii)当然真正公开时,ApplicationSettings 才有用。如果这两种情况都不成立,那么这并不理想,您的选择又回到了 .config 文件 .resx
In my opinion ApplicationSettings is only useful if your settings are (i) genuinely constants and (ii) of course truly public. If either of these cases is not true then this is not ideal and your choice is back to a .config file .resx
嗯,我认为 ApplicationStrings 是一个很好的解决方案
Well, I think that ApplicationStrings is a good solution