
您在專案中建立自訂設定部分時遇到問題。讓我們分解您的問題並提供全面的解決方案:
您的 App.config 檔案似乎已正確配置。它定義了一個名為「ServicesSection」的自訂部分及其類型處理程序。
您的 ServiceConfig 和 ServiceCollection 類別已正確定義,與預期的配置節結構相符。
您正確地不再使用已棄用的 IConfigurationSectionHandler 介面。相反,您應該建立一個派生自 ConfigurationSection 的新類別:
public class ServiceConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("Services", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(ServiceCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public ServiceCollection Services
{
get
{
return (ServiceCollection)base["Services"];
}
}
}在此類中,「Services」屬性定義為 ServiceCollection 類型的 ConfigurationCollection。這為分層配置結構奠定了基礎。
定義了ConfigurationSection 後,您可以如下存取其資料:
ServiceConfigurationSection serviceConfigSection =
ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;
ServiceConfig serviceConfig = serviceConfigSection.Services[0];透過以下方式透過這些步驟,您應該能夠使用ConfigurationElementCollection 成功實作自訂配置部分。
以上是如何在 .NET 中使用 ConfigurationElementCollection 實作自訂配置節?的詳細內容。更多資訊請關注PHP中文網其他相關文章!