我有一個工作的自定義配置節。然而,這是一個痛苦通過ConfigurationElementCollection
但是當我試圖實現我的財產作爲一個IEnumerable,它失敗,出現錯誤,在我的數據獲取:具有非ConfigurationElement屬性的自定義配置節
ConfigurationErrorsException was unhandled "Property 'contacts' is not a ConfigurationElement."
這裏是代碼導致故障:
[ConfigurationProperty("contacts", IsDefaultCollection = false)]
public IEnumerable<string> Contacts
{
get { return ((ContactCollection)base["contacts"]).Cast<ContactElement>().Select(x => x.Address); }
}
但是,如果我把它改成這樣:
[ConfigurationProperty("contacts", IsDefaultCollection = false)]
public ContactCollection Contacts
{
get { return ((ContactCollection)base["contacts"]); }
}
,一切工作正常。 This答案聽起來像這只是微軟決定不允許的東西,所以我不能有除ConfigurationElement
以外的任何其他類型的屬性。這是真的嗎?我如何才能以IEnumerable<string>
實現我的財產?
萬一它很重要,我正在嘗試存儲電子郵件,並且我希望爲每個電子郵件分配一個元素,因爲可能會有多個元素,我們可能會在將來爲每個聯繫人存儲更多信息,我認爲一個以逗號分隔的列表可能會變得很難看。例如,像:
<emergency>
<contact address="[email protected]" />
<contact address="[email protected]" />
</emergency>
或者
<emergency>
<contact>[email protected]</contact>
<contact>[email protected]</contact>
</emergency>
謝謝!
你有我的同情心。自定義配置節與嵌套集合是一個巨大的痛苦。我已經寫了很多,但我仍然記不起語法來提供答案。也許這篇文章會幫助:[http://stackoverflow.com/questions/10958054/how-to-create-a-configuration-section-that-contains-a-collection-of-collections](http://stackoverflow。 com/questions/10958054/how-to-create-a-configuration-section-that-contain-a-collection-of-collections) –
在我看來,大部分複雜性來自於支持以編程方式更新的部分支持覆蓋較低級別的配置文件。這很棒,但實際上我們很少使用它。說我們從不*使用它可能是安全的。 –