how to have custom attribute in ConfigurationElementCollection?

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

for configuration as following


  
  ... other entries
         


        
4条回答
  •  旧时难觅i
    2020-12-23 19:17

    Let's suppose you have this .config file:

    
        
            
    // update type & assembly names accordingly

    Then, with this code:

    public class MySection : ConfigurationSection
    {
        [ConfigurationProperty("MyCollection", Options = ConfigurationPropertyOptions.IsRequired)]
        public MyCollection MyCollection
        {
            get
            {
                return (MyCollection)this["MyCollection"];
            }
        }
    }
    
    [ConfigurationCollection(typeof(EntryElement), AddItemName = "entry", CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class MyCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new EntryElement();
        }
    
        protected override object GetElementKey(ConfigurationElement element)
        {
            if (element == null)
                throw new ArgumentNullException("element");
    
            return ((EntryElement)element).Name;
        }
    
        [ConfigurationProperty("default", IsRequired = false)]
        public string Default
        {
            get
            {
                return (string)base["default"];
            }
        }
    }
    
    public class EntryElement : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
        public string Name
        {
            get
            {
                return (string)base["name"];
            }
        }
    }
    

    you can read the configuration with the 'default' attribute, like this:

        MySection section = (MySection)ConfigurationManager.GetSection("mySection");
        Console.WriteLine(section.MyCollection.Default);
    

    This will output "one"

提交回复
热议问题