存储程序使用的一组常量的最佳方法是什么?

我有各种常量,我的程序使用... ... string的,int的,double的,等等。.存储它们的最佳方法是什么?我不认为我想要一个 Enum,因为数据不是全部相同的类型,我想手动设置每个值。我是不是应该把它们都放在一个空教室里?还是有更好的办法?

123283 次浏览

IMO 使用一个充满常量的类对于常量来说是很好的。如果它们偶尔会发生变化,我建议在配置中使用 AppSettings,而不是 ConfigurationManager 类。

当我有从 AppSettings 或类似设置中实际提取的“常量”时,我仍然总是有一个“常量”类来包装从配置管理器的读取。它总是更有意义的有 Constants.SomeModule.Setting而不是直接诉诸于 ConfigurationManager.AppSettings["SomeModule/Setting"]在任何地方,要消费所说的设置价值。

这种设置的额外好处是,因为 SomeModule很可能是 Constants 文件中的一个嵌套类,所以你可以很容易地使用依赖注入将其中一个直接注入到依赖它的类中。你甚至可以在 SomeModule之上提取一个接口,然后在你使用的代码中创建一个对 ISomeModuleConfiguration的依赖关系,这将允许你解耦对 Constants 文件的依赖关系,甚至可能使测试变得更容易,特别是如果这些设置来自 AppSettings 并且你使用配置转换来改变它们,因为这些设置是特定于环境的。

您可以将它们放在具有静态只读属性的静态类中。

public static class Routes
{
public static string SignUp => "signup";
}

我喜欢做的事情如下(但是一定要读到最后使用正确的 常数的类型常数的类型) :

internal static class ColumnKeys
{
internal const string Date = "Date";
internal const string Value = "Value";
...
}

阅读此 了解为什么 const可能不是你想要的。可能的 常数的类型常数的类型是:

  • const磁场。如果将来值 也许吧更改,则不要跨程序集使用(publicprotected) ,因为该值将在其他程序集的编译时硬编码。如果更改该值,则其他程序集将使用旧值,直到重新编译为止。
  • static readonly磁场
  • 没有 setstatic属性

空静态类是合适的。可以考虑使用几个类,这样就可以得到很好的相关常量组,而不是一个巨大的 Globals.cs 文件。

另外,对于一些 int 常量,考虑下表示法:

[Flags]
enum Foo
{
}

因为这考虑到了 treating the values like flags

是的,使用 static class存储常量就可以了,但与特定类型相关的常量除外。

Another vote for using web.config or app.config. The config files are a good place for constants like connection strings, etc. I prefer not to have to look at the source to view or modify these types of things. A static class which reads these constants from a .config file might be a good compromise, as it will let your application access these resources as though they were defined in code, but still give you the flexibility of having them in an easily viewable/editable space.

这是 IMO 的最佳方式,不需要属性或只读:

public static class Constants
{
public const string SomeConstant = "Some value";
}

如果这些常量是影响应用程序行为的服务引用或开关,我会将它们设置为应用程序用户设置。这样,如果需要更改它们,就不必重新编译,而且仍然可以通过静态属性类引用它们。

Properties.Settings.Default.ServiceRef

我建议使用带有静态 readonly 的静态类。请找到下面的代码片段:

  public static class CachedKeysManager
{
public static readonly string DistributorList = "distributorList";
}