您将如何管理每个 C# 类的常量?
在所有应用中,总会使用一些常量值。
我不喜欢在应用程序的每个代码中对这些值进行硬编码,因为这会显着降低可维护性。
我有 2 个选项:
在目标类中创建一个内部 Constants 类并添加公共 const 值,例如
内部静态类常量 { 公共常量字符串IdAttribute =“id”; 在目标
创建一个资源文件 (.resx)并
- 在其中存储我的常量值和公式。
我在这里的应用程序中使用了第二种方法。我在使用资源文件时遇到的一个问题是我无法使用它们的 .NET 4.0 可选参数功能。
例如,以下内容不起作用:
public void DoSomething(string id = Resources.Constants.Id)
{
// ..
}
错误是 Id 的值未在运行时确定。
基本上,您会使用并推荐哪种方式来管理每个类的常量?为什么?
我当前的方法是,如果我有只应在一个类中使用的常量,我会在该类中创建一个静态常量类。如果我的常量要在多个类或项目中使用,我会将它们放入资源文件中,例如 PageUrls.resx。
谢谢,
In all applications, there are always some constant values that are used.
I don't like hardcoding these values in my application in each code as it reduces maintainability significantly.
I have 2 options:
Create an internal Constants class within your target class and add public const values such as
internal static class Constants
{
public const string IdAttribute = "id";
}
or
- Create a Resource file (.resx) and store my constant values and formulas there.
I have used the second approach in my application here. One issue I had with using a resource file was that I could not use .NET 4.0 Optional Parameter feature with them.
e.g. the below doesn't work:
public void DoSomething(string id = Resources.Constants.Id)
{
// ..
}
The error was that the value of Id is not determined at runtime.
Basically, which way would you use and recommend to manage your constants for each class? why?
My current approach is that if I have constants that should be used inside one class only, I create a static Constants class inside that class. If my constants are to be used in more than one class or project, I'll put them in a resource file e.g. PageUrls.resx.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就我个人而言,我宁愿在逻辑上所属的类中定义常量,类似于(例如)
DateTime.MinValue
。然后,一般来说,公开这些常量有点“代码味道”,这意味着一些耦合可能应该以更好的方式表达。当您的代码允许时,将它们设置为私有(或内部)显然没有什么坏处。
然而,有时存在属于全局的总体常数。这些实际上通常是配置,应该如此对待。
Personally I'd rather have constants defined in the classes where they logically belong, in a similar way to (say)
DateTime.MinValue
.Then, in general making these constants public is a bit of a "code smell", implying some coupling that should probably be expressed in a better way. There's obviously no harm in making them private (or internal) when your code allows.
Sometimes there are overall constants that belong globally, however. These are often actually configuration and should be treated as such.
我个人主要将资源用于呈现给用户的常量。主要优点是可以将其本地化。
对于内部常量,我更喜欢
static readonly 到
const
变量。当它们被许多类共享时,我会将它们放入常量类中,否则放入需要它们的类中
I personally use resources mostly for constants that are presented to the user. The main advantage is the possibility to localize it.
For internal constants I prefer
static readonly
toconst
variables. When they are shared by many classes I would put them into a constants class, otherwise in the class where they are needed