.Net 設定檔——繼承ConfigurationSection實現自訂處理類處理自訂配置節點

來源:互聯網
上載者:User
除了使用繼承IConfigurationSectionHandler的方法定義處理自訂節點的類,還可以通過繼承ConfigurationSection類實現同樣效果。

首先說下.Net設定檔中一個潛規則

在配置節點時,對於想要進行儲存的參數資料,可以採用兩種方式:一種是儲存到節點的屬性中,另一種是儲存在節點的文本中。

因為一個節點可以有很多屬性,但是只要一個innertext,而要在程式中將這兩種形式區分開會帶來複雜性。 為了避免這個問題,.net的設定檔只是用屬性儲存區而不使用innertext.


接著,我們來寫一個符合這個潛規則的自訂設定檔,方便測試:

<mailServerGroup provider="www.baidu.com">    <mailServers>      <mailServer client="http://blog.csdn.net/lhc1105" address="13232@qq.com" userName="lhc" password="2343254"/>      <mailServer client="http://blog345.csdn.net/lhc1105" address="132wdfgdsggtaewg32@qq.com" userName="dfshs水田如雅"  password="2334t243的薩芬234254"/>      <mailServer client="http://blog436.csdn.net/lhc1105" address="132wdgadsfgdtaewg32@qq.com" userName="sdfhdfs水田如雅"  password="23ewrty2343的薩芬234254"/>      <mailServer client="http://blo345734g.csdn.net/lhc1105" address="132wdgdfagdstaewg32@qq.com" userName="sdfher水田如雅"  password="23erwt43的薩芬234254"/>    </mailServers>  </mailServerGroup>

接著,我們來寫相應的處理類,這裡我們由內向外來寫:

首先是最內層的mailServer:

 /// <summary>    /// Class MailServerElement:用於映射mailServer節點,這裡是實際儲存資料的地方;    /// </summary>    /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:51:57</remarks>    public sealed class MailServerElement : ConfigurationElement  //設定檔中的配置元素    {        /// <summary>        /// Gets or sets the client.        /// </summary>        /// <value>The client.</value>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:40</remarks>        [ConfigurationProperty("client", IsKey = true, IsRequired = true)]  //client是必須的key屬性,有點兒主鍵的意思,例如,如果定義多個client相同的節點,迴圈讀取的話就唯讀取到最後一個值        public string Client        {            get            {                return this["client"] as string;            }            set            {                this["client"] = value;            }        }        /// <summary>        /// Gets or sets the address.        /// </summary>        /// <value>The address.</value>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:38</remarks>        [ConfigurationProperty("address")]        public string Address        {            get            {                return this["address"] as string;            }            set            {                this["address"] = value;            }        }        /// <summary>        /// Gets or sets the name of the user.        /// </summary>        /// <value>The name of the user.</value>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:35</remarks>        [ConfigurationProperty("userName")]        public string UserName        {            get            {                return this["userName"] as string;            }            set            {                this["userName"] = value;            }        }        /// <summary>        /// Gets or sets the password.        /// </summary>        /// <value>The password.</value>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:33</remarks>        [ConfigurationProperty("password")]        public string Password        {            get            {                return this["password"] as string;            }            set            {                this["password"] = value;            }        }    }

接著是mailServers,它是一個mailServer的集合:

 /// <summary>    /// Class MailServerCollection:映射mailServers節點,為一個集合類,另外還包含了很多對節點的操作方法,大部分繼承自ConfigurationElementCollection    /// </summary>    /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:52:00</remarks>    public sealed class MailServerCollection : ConfigurationElementCollection    {        /// <summary>        /// 擷取 <see cref="T:System.Configuration.ConfigurationElementCollection" /> 的類型。        /// </summary>        /// <value>The type of the collection.</value>        /// <returns>此集合的 <see cref="T:System.Configuration.ConfigurationElementCollectionType" />。</returns>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:08</remarks>        public override ConfigurationElementCollectionType CollectionType        {            get            {                return ConfigurationElementCollectionType.BasicMap;            }                 }        /// <summary>        /// 當在派生的類中重寫時,建立一個新的 <see cref="T:System.Configuration.ConfigurationElement" />。        /// </summary>        /// <returns>新的 <see cref="T:System.Configuration.ConfigurationElement" />。</returns>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:03</remarks>        protected override ConfigurationElement CreateNewElement()        {            return new MailServerElement();        }        /// <summary>        /// 在衍生類別中重寫時擷取指定配置元素的元素鍵。        /// </summary>        /// <param name="element">要為其返回鍵的 <see cref="T:System.Configuration.ConfigurationElement" />。</param>        /// <returns>一個 <see cref="T:System.Object" />,用作指定 <see cref="T:System.Configuration.ConfigurationElement" /> 的鍵。</returns>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:04:51</remarks>        protected override object GetElementKey(ConfigurationElement element)        {            return (element as MailServerElement).Client;        }        /// <summary>        /// 擷取在派生的類中重寫時用於標識設定檔中此元素集合的名稱。        /// </summary>        /// <value>The name of the element.</value>        /// <returns>集合的名稱;否則為空白字串。預設值為空白字串。</returns>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 23:41:40</remarks>        protected override string ElementName        {            get            {                return "mailServer";            }        }        /// <summary>        /// 擷取集合中的元素數。        /// </summary>        /// <value>The count.</value>        /// <returns>集合中的元素數。</returns>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:08:24</remarks>        public new int Count        {            get { return base.Count; }        }        /// <summary>        /// 擷取或設定此配置元素的屬性、特性或子項目。        /// </summary>        /// <param name="index">The index.</param>        /// <returns>MailServerElement.</returns>        /// <remarks>Editor:v-liuhch</remarks>        public MailServerElement this[int index]        {            get { return BaseGet(index) as MailServerElement; }            set            {                if (BaseGet(index) != null)                {                    BaseRemoveAt(index);                }                BaseAdd(index, value);            }        }        /// <summary>        /// 擷取或設定此配置元素的屬性、特性或子項目。        /// </summary>        /// <param name="Name">The name.</param>        /// <returns>MailServerElement.</returns>        /// <remarks>Editor:v-liuhch</remarks>        new public MailServerElement this[string Name]        {            get { return BaseGet(Name) as MailServerElement; }        }        /// <summary>        /// Indexes the of.        /// </summary>        /// <param name="element">The element.</param>        /// <returns>System.Int32.</returns>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:24:16</remarks>        public int IndexOf(MailServerElement element)        {            return BaseIndexOf(element);        }        /// <summary>        /// Adds the specified element.        /// </summary>        /// <param name="element">The element.</param>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:26:06</remarks>        public void Add(MailServerElement element)        {            BaseAdd(element);        }        /// <summary>        /// Removes the specified element.        /// </summary>        /// <param name="element">The element.</param>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:27:01</remarks>        public void Remove(MailServerElement element)        {            if (BaseIndexOf(element) > 0)            {                BaseRemove(element.Client);            }        }        /// <summary>        /// Removes at.        /// </summary>        /// <param name="index">The index.</param>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:33:29</remarks>        public void RemoveAt(int index)        {            BaseRemoveAt(index);        }        /// <summary>        /// Removes the specified client.        /// </summary>        /// <param name="client">The client.</param>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:34:04</remarks>        public void Remove(string client)        {            BaseRemove(client);        }        /// <summary>        /// Clears this instance.        /// </summary>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:34:29</remarks>        public void Clear()        {            BaseClear();        }    }

最後是最外層的group:

 /// <summary>    /// Class MailServerSection 為入口:    /// </summary>    /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:41:02</remarks>    public class MailServerSection : ConfigurationSection   //繼承設定檔中節    {        /// <summary>        /// Gets the provider.:映射mailServerGroup節點的provider        /// </summary>        /// <value>The provider.</value>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:59</remarks>        [ConfigurationProperty("provider", IsKey = true)]        public string provider { get { return this["provider"] as string; } }        /// <summary>        /// Gets or sets the mail servers.:映射新添加的節點mailServers節點;這個節點下還包含了若干個mailServer節點,因此它是一個集合類        /// </summary>        /// <value>The mail servers.</value>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:56</remarks>        [ConfigurationProperty("mailServers", IsDefaultCollection = false)]        public MailServerCollection MailServers        {            get            {                return this["mailServers"] as MailServerCollection;            }            set            {                this["mailServers"] = value;            }        }    }

同樣,關聯處理類和節點:

 <section name="mailServerGroup" type="繼承ConfigurationSection基類.MailServerSection,繼承ConfigurationSection基類"/>     </configSections>

之後做個測試:

class Program    {        static void Main(string[] args)        {            Test();        }        /// <summary>        /// Tests this instance.:讀取節點值樣本        /// </summary>        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 23:04:53</remarks>        private static void Test() {            MailServerSection mailSection = (MailServerSection)ConfigurationManager.GetSection("mailServerGroup");            Console.WriteLine("MailServerSection 的provider屬性值:"+mailSection.provider);            foreach (MailServerElement config in mailSection.MailServers)            {                Console.WriteLine("----------------------------------");                Console.WriteLine("client值為:"+config.Client);                Console.WriteLine("address值為:"+config.Address);                Console.WriteLine("username值為:"+config.UserName);                Console.WriteLine("password值為:"+config.Password);                Console.WriteLine("----------------------------------");            }            Console.ReadKey();        }    }

本來還想傳張結果圖,但是網速慢,算啦,喜歡玩兒的童鞋自己run下結果。。。。。

以上就是.Net 設定檔——繼承ConfigurationSection實現自訂處理類處理自訂配置節點 的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!




  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.