簡體   English   中英

如何創建不同類型的多個配置項

[英]How to create multiple configuration items of different types

是否可以具有如下所示的不同類型的配置項目列表?

<exceptions>
  <exception name ="exception1" host="myhostname">
    <block user="joe"/>
    <block user="peter"/>
    <allow user="admin"/>
  </exception>
  <exception name ="exception2" host="anotherhostname">
    <block user="sue"/>
    <block user="danny"/>
    <allow user="johnny"/>
  </exception>
</exceptions>

我正在嘗試定義一個配置,該配置允許我阻止或允許用戶使用給定的主機名。 如果我只有<allow>類型的元素,那將很容易:

[ConfigurationCollection(typeof(AllowElement))]
class AllowCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new AllowElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((AllowElement) element).User;
    }

    public AllowElement this[int index]
    {
        get { return (AllowElement) BaseGet(index); }
    }

    public new AllowElement this[string key]
    {
        get { return (AllowElement) BaseGet(key); }
    }
}

class AllowElement : ConfigurationElement
{
    [ConfigurationProperty("user", IsKey = true, IsRequired = true)]
    public string User
    {
        get { return (string) base["user"]; }
    }
}

如何添加<block>配置項? 真的有可能嗎?

基本上,您必須重寫IsElementName才能提供對有效項目名稱的檢查(在您的情況下為阻止並允許)。 您還需要將這些有效值作為逗號分隔的字符串映射到ConfigurationCollection的AddItem name屬性。

您還必須重寫CollectionType才能返回ConfigurationElementCollectionType.BasicMapAlternate

然后,您需要將自己的AllowElement更改為將同時支持allow和block的通用元素。 該鏈接示例使用一個Enum,但是您可以做任何您想做的事情。 在CreateNewElement上,您將處理elementName並返回具有正確類型標識符的通用元素集。

這是Derek的鏈接,您可以在名為Collection items的部分中找到我建議的實現,其中元素名稱不同

很抱歉復制粘貼的鏈接,但是我想指向解決方案的鏈接看上去比您的需求要好,而該解決方案的鏈接比類名不同而沒有任何其他問題的代碼大。

暫無
暫無

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

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