代码改变世界

自定义配置节点

2013-01-10 18:04  Carl Xing  阅读(182)  评论(0编辑  收藏  举报

创建工程,添加文件:

Program调用,ConfigSection用于配置,Configs为节点集合,Config为实际应用节点。

App.Config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="ConfigSection" type="ConfigurationTest.ConfigSection,ConfigurationTest"/>
  </configSections>
  <ConfigSection>
    <Configs>
      <Config name="config1" value="CONFIG1"/>
    </Configs>
  </ConfigSection>
</configuration>

Program:

class Program
    {
        static void Main(string[] args)
        {
            ConfigSection section = ConfigurationManager.GetSection("ConfigSection") as ConfigSection;
            foreach (Config config in section.Configs)
            {
                Console.WriteLine(config.Name + ":" + config.Value);
            }

            Console.ReadLine();
        }
    }

ConfigSection:

public class ConfigSection:ConfigurationSection
    {

        /// <summary>
        /// 配置项集合
        /// </summary>
        [ConfigurationProperty("Configs")]
        public Configs Configs
        {
            get { return this["Configs"] as Configs; }
            set { this["Configs"] = value; }
        }
    }

Configs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace ConfigurationTest
{
    public class Configs:ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new Config();
        }

        /// <summary>
        /// 元素名
        /// </summary>
        protected override string ElementName
        {
            get
            {
                return "Config";
            }
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            Config el = element as Config;
            return el.Name;
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        } 
    }
}

Config:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace ConfigurationTest
{
    public class Config:ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get { return this["name"] as string; }
            set { this["name"] = value; }
        }

        [ConfigurationProperty("value", IsRequired = true)]
        public string Value
        {
            get { return this["value"] as string; }
            set { this["value"] = value; }
        }
    }
}