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

带有简单“添加”元素列表的自定义app.config部分

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

带有简单“添加”元素列表的自定义app.config部分

带有基于OP config文件的代码的完整示例:

<configuration>    <configSections>        <section name="registerCompanies"       type="My.MyConfigSection, My.Assembly" />    </configSections>    <registerCompanies>        <add name="Tata Motors" pre="Tata"/>        <add name="Honda Motors" pre="Honda"/>    </registerCompanies></configuration>

这是示例示例,用于实现折叠集合的自定义配置部分

using System.Configuration;namespace My {public class MyConfigSection : ConfigurationSection {    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]    public MyConfigInstanceCollection Instances {        get { return (MyConfigInstanceCollection)this[""]; }        set { this[""] = value; }    }}public class MyConfigInstanceCollection : ConfigurationElementCollection {    protected override ConfigurationElement CreateNewElement() {        return new MyConfigInstanceElement();    }    protected override object GetElementKey(ConfigurationElement element) {        //set to whatever Element Property you want to use for a key        return ((MyConfigInstanceElement)element).Name;    }}public class MyConfigInstanceElement : ConfigurationElement {    //Make sure to set IsKey=true for property exposed as the GetElementKey above    [ConfigurationProperty("name", IsKey = true, IsRequired = true)]    public string Name {        get { return (string) base["name"]; }        set { base["name"] = value; }    }    [ConfigurationProperty("pre", IsRequired = true)]    public string Code {        get { return (string) base["pre"]; }        set { base["pre"] = value; }    } } }

这是如何从代码访问配置信息的示例。

var config = ConfigurationManager.GetSection("registerCompanies")       as MyConfigSection;Console.WriteLine(config["Tata Motors"].Code);foreach (var e in config.Instances) {    Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code); }


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

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

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