栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在app.config中创建自定义配置部分?[重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在app.config中创建自定义配置部分?[重复]

导入名称空间:

using System.Configuration;

创建ConfigurationElement公司:

public class Company : ConfigurationElement{        [ConfigurationProperty("name", IsRequired = true)]        public string Name        { get {     return this["name"] as string; }        } [ConfigurationProperty("pre", IsRequired = true)]        public string Code        { get {     return this["pre"] as string; }        }}

ConfigurationElementCollection:

public class Companies        : ConfigurationElementCollection    {        public Company this[int index]        { get {     return base.baseGet(index) as Company ; } set {     if (base.baseGet(index) != null)     {         base.baseRemoveAt(index);     }     this.baseAdd(index, value); }        }       public new Company this[string responseString]       { get { return (Company) baseGet(responseString); } set {     if(baseGet(responseString) != null)     {         baseRemoveAt(baseIndexOf(baseGet(responseString)));     }     baseAdd(value); }        }        protected override System.Configuration.ConfigurationElement CreateNewElement()        { return new Company();        }        protected override object GetElementKey(System.Configuration.ConfigurationElement element)        { return ((Company)element).Name;        }    }

和ConfigurationSection:

public class RegisterCompaniesConfig        : ConfigurationSection    {        public static RegisterCompaniesConfig GetConfig()        { return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();        }        [System.Configuration.ConfigurationProperty("Companies")] [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]        public Companies Companies        { get {     object o = this["Companies"];     return o as Companies ; }        }    }

并且您还必须在web.config(app.config)中注册新的配置部分:

<configuration><configSections>          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

然后你用

var config = RegisterCompaniesConfig.GetConfig();foreach(var item in config.Companies){   do something ..}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/395400.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号