ConfigurationPropertyCollection是否需要是静态的?

时间:2011-06-12 14:45:35

标签: c# .net configuration

根据这篇经常引用的文章Unraveling the Mysteries of .NET Configuration,在实现ConfigurationSection / ConfigurationElement时,建议遵循以下模式:

private static ConfigurationPropertyCollection s_properties;
static ExampleSection()
{
        // Predefine properties here
        // Add the properties to s_properties
}

/// Override the Properties collection and return our custom one.
protected override ConfigurationPropertyCollection Properties
{
    get { return s_properties; }
}

但它没有解释为什么 s_properties字段需要是静态的,并且属性在静态构造函数中初始化。
毕竟,它只能通过非静态Properties覆盖属性...

访问

(我有一套复杂的自定义配置管理,它会大大简化s_properties字段不是静态的事情......)

那么,是否有一些直接访问静态字段的“隐藏”访问?是否会不断创建和重新创建Configuration***对象,这样对象级字段就会丢失,因此效率低下?
或者将ConfigurationPropertyCollection存储和初始化为非静态是完全正常的吗?

1 个答案:

答案 0 :(得分:2)

  

但它没有解释为什么s_properties字段需要是静态的,

s_properties是静态的原因是因为开发人员只需要一组应用程序的配置属性 - 单例实例。 [这可能被认为是典型的。] ConfigurationXXX(例如,ConfigurationManager)类是静态的,因为每个AppDomain只需要一个。

基本上,在样本中:

private static ConfigurationPropertyCollection s_properties;
static ExampleSection()
{
        // Predefine properties here
        // Add the properties to s_properties
}

/// Override the Properties collection and return our custom one.
protected override ConfigurationPropertyCollection Properties
{
    get { return s_properties; }
}

作者假设您应该只有s_properties的单个实例。

  

那么,是否有一些直接访问静态字段的“隐藏”访问?

不确定我是否关注此问题。

  

Configuration ***对象是否不断创建和重新创建,这样对象级字段就会丢失,因此效率低下?

[编辑:取决于...我正在考虑ConfigurationManager。但是,说我想拥有AppSettingsCollection的本地副本。我会做一个静态只读字段声明。在章节等的上下文中然后我仍然会使用静态字段inializer,尽管是static Dictionary<string, ConfigurationPropertyCollection> Properties。最后,我仍然相信您只需要一个属性设置集合的单个实例。]

[原创与其他[编辑]]
不。[静态]不会不断创建,处理和重新创建ConfigurationXXX对象。与所有静态对象一样,公共静态初始化器/构造函数一次执行 - 第一次调用该对象。例如,当我打电话给以下人员时:

string someValue = ConfigurationManager.AppSettings["SomeKey"];  

执行静态ConfigurationManager类构造函数。由于此类是静态的,因此它将在执行它的当前AppDomain的生命周期中存在。

我不建议将应用域属性,配置属性或属性集初始化为实例类。当程序开始执行时,您应该依赖静态Configuration类,在该类中包装和自定义与ConfigurationXXX类,成员和函数的交互。