对自定义配置节点的一些简单认识

在实现一个自定义的配置时,一直很纳闷为什么ConfigurationProperty会被定义为static readonly字段,在查阅相关资料后,终于弄明白,ConfigurationProperty本身并不存储属性的具体的值,而只是存储了相关的键,比如这里的address、name,可以理解为是通过ConfigurationProperty来实现对相应的自定义配置节点结构的存储,而不是相关具体内容的存储。

通过ConfigurationPropertyCollection来存储相关的ConfigurationProperty,这个ConfigurationPropertyCollection可以是在自己扩展的类中来添加也可以使用基类中的Properties属性,不过如果使用基类的Properties则需要在相应的构造函数中把ConfigurationProperty加入到Properties中。

以下分类是两种扩展的实现方式:

一、 通过自己添加的ConfigurationPropertyCollection来来实现

    public class MailAddressElement: ConfigurationElement
    {
         private static readonly ConfigurationProperty _address = new ConfigurationProperty("address", typeof(string), String.Empty, ConfigurationPropertyOptions.IsKey);
        private static readonly ConfigurationProperty _name = new ConfigurationProperty("name", typeof(string), String.Empty, ConfigurationPropertyOptions.None);
        private static ConfigurationPropertyCollection _properties = new ConfigurationPropertyCollection();

        static MailAddressElement()   // 使用了静态构造函数
        {
            _properties.Add(_address);  // 使用了自定义的ConfigurationPropertyCollection 
            _properties.Add(_name);
        }

        public string Address
        {
            get {return (string)this[_address];}
        }
        public string Name
        {
            get { return (string)this[_name]; }
        }

        protected override ConfigurationPropertyCollection Properties  // 覆盖了基类的Properties属性
        {
            get
            {
                return _properties;
            }
        }
    }

二、使用基类的Properties

    public class MailAddressElement: ConfigurationElement
    {
         private static readonly ConfigurationProperty _address = new ConfigurationProperty("address", typeof(string), String.Empty, ConfigurationPropertyOptions.IsKey);
        private static readonly ConfigurationProperty _name = new ConfigurationProperty("name", typeof(string), String.Empty, ConfigurationPropertyOptions.None);
        public MailAddressElement()  // 采用了实例构造函数
        {
            Properties.Add(_address); // 这里的Properties继承自基类
            Properties.Add(_name);
        }

        public string Address
        {
            get {return (string)this[_address];}
        }
        public string Name
        {
            get { return (string)this[_name]; }
        }

    }


 

原文地址:https://www.cnblogs.com/mincyw/p/1351032.html