how to have custom attribute in ConfigurationElementCollection?

后端 未结 4 708
深忆病人
深忆病人 2020-12-23 18:34

for configuration as following


  
  ... other entries
         


        
4条回答
  •  情话喂你
    2020-12-23 18:55

    This may be a bit late but may be helpful to others.

    It is possible but with some modification.

    • ConfigurationElementCollection inherits ConfigurationElement as such "this[string]" is available in ConfigurationElement.

    • Usually when ConfigurationElementCollection is inherited and implemented in another class, the "this[string]" is hidden with "new this[string]".

    • One way to get around it is to create another implementation of this[] such as "this[string, string]"

    See example below.

    public class CustomCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new CustomElement();
        }
    
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((CustomElement)element).Name;
        }
    
        public CustomElement this[int index]
        {
            get { return (CustomElement)base.BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                    BaseRemoveAt(index);
    
                BaseAdd(index, value);
            }
        }
    
        // ConfigurationElement this[string] now becomes hidden in child class
        public new CustomElement this[string name]
        {
            get { return (CustomElement)BaseGet(name); }
        }
    
        // ConfigurationElement this[string] is now exposed
        // however, a value must be entered in second argument for property to be access
        // otherwise "this[string]" will be called and a CustomElement returned instead
        public object this[string name, string str = null]
        {
            get { return base[name]; }
            set { base[name] = value; }
        }
    }
    

提交回复
热议问题