获得System.Configure的两种高级用法

1.最简单的可以用继承IConfigurationSectionHandler来实现读取configure

  public class WebAddresssSectionHandler : IConfigurationSectionHandler
    {
        public virtual object Create(object parent, object configContext, XmlNode section)
        {
            WebAddresss webAddresss = new WebAddresss();
            if (section != null)
            {
                foreach (XmlNode item in section.SelectNodes("WebAddress"))
                {
                    WebAddress webAddress = new WebAddress();
                    foreach (XmlAttribute attribute in item.Attributes)
                    {
                        switch (attribute.Name)
                        {
                            case "Type":
                                webAddress.Type = attribute.Value;
                                break;
                            case "Name":
                                webAddress.Name = attribute.Value;
                                break;
                            case "Url":
                                webAddress.Url = attribute.Value;
                                break;
                            default:
                                break;
                        }
                    }
                    webAddresss[webAddress.Name] = webAddress;
                }
            }
            return webAddresss;
        }
    }

WebAddress就是数据类:

  public class WebAddress
    {
        public string Type { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
    }
对外只要实现一个获取配置的current实例来枚举:

  public class WebAddresss
    {
        protected Dictionary _webAddresses=new Dictionary();

        private static WebAddresss _currentAddresss = null;

        public virtual WebAddress this[string name]
        {
            get { return _webAddresses[name]; }
            set { _webAddresses[name] = value; }
        }

        public static WebAddresss Current
        {
            get
            {
                if (_currentAddresss == null)
                {
                    _currentAddresss= System.Configuration.ConfigurationManager.GetSection("WebAddresss") as WebAddresss;
                }
                return _currentAddresss;
            }
        }
    }

对应这个web.config就能如下配置:


  
    

你可能感兴趣的:(c#)