簡體   English   中英

ConfigurationPropertyCollection 是否需要為 static?

[英]Does ConfigurationPropertyCollection need to be static?

根據這篇經常引用的文章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字段需要是 static,以及在 static 構造函數中初始化的屬性。
畢竟,它只能通過非靜態Properties覆蓋的屬性來訪問......

(我有一套復雜的自定義配置管理,它將大大簡化s_properties字段不是 static 的事情......)

那么,是否有一些直接對 static 字段的“隱藏”訪問? Configuration*** object 是否不斷創建和重新創建,從而導致對象級字段丟失,因此效率低下?
或者將ConfigurationPropertyCollection存儲和初始化為非靜態是否完全可以?

但它沒有解釋為什么 s_properties 字段需要是 static,

s_properties static 的原因是因為開發人員只需要一組 - singleton 實例 - 應用程序的配置屬性。 [這可能被認為是典型的。] ConfigurationXXX(例如,ConfigurationManager)類是 static,因為每個 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實例。

那么,是否有一些直接對 static 字段的“隱藏”訪問?

不確定我是否遵循這個問題。

配置*** object 是否不斷創建和重新創建,從而導致對象級字段丟失,因此效率低下?

[編輯:取決於...我正在考慮配置管理器。 但是,假設我想要我的 AppSettingsCollection 的本地副本。 我會做一個 static 只讀字段聲明。 在 Sections 等的上下文中,我仍然會使用 static 字段初始化程序,盡管是static Dictionary<string, ConfigurationPropertyCollection> Properties 最后,我仍然相信您只需要一個屬性設置集合的實例。 ]

[原創與其他[編輯]]
否。 [ Static ] ConfigurationXXX 對象不會不斷創建、處置和重新創建。 像所有 static 對象一樣,公共 static 初始化器/構造器被執行一次 - 第一次調用 object。 例如,當我調用以下命令時:

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

執行 static ConfigurationManager class 構造函數。 由於此 class 是 static,因此它將在執行它的當前 AppDomain 的生命周期內存活。

我不建議將應用程序域屬性、配置屬性或屬性 collections 作為 或在 實例 class 中初始化。 當您的程序開始執行時,您應該依賴 static 配置 class,您可以在其中包裝和自定義與 ConfigurationXXX 類、成員和函數的交互。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM