【问题标题】:How do I use User settings and Custom Configuration Sections in app.config? [duplicate]如何在 app.config 中使用用户设置和自定义配置部分? [复制]
【发布时间】:2014-09-06 23:50:31
【问题描述】:

如何使用 app.config 中的用户设置和自定义配置部分?

 <mySection id="myId">
    <item1 data="info">
    <item2 data="more info">
</mySection>

并将它们链接到一个类型。

【问题讨论】:

    标签: c#


    【解决方案1】:

    app.config

    键值对去哪儿了?

    appSettings
    

    怎么样?举个例子

     <add key="File_Count" value="2" />
    

    .cs

    什么类可以访问用户设置?

     System.Configuration.ConfigurationManager
    

    项目必须参考什么?

     System.Configuration
    

    哪种方法给出了基本设置?以上示例

     AppSettings["File_Count"]
    

    鉴于以下自定义部分

     <mySection id="myId">
        <item1 data="info">
        <item2 data="more info">
    </mySection>
    

    对于“myAssembly”中名为“Sample.myType”的类类型,需要在应用文件中声明什么?

    <configSections>
      <section name="mySection" type="Sample.myType, myAssembly" />
    </configSections>
    

    xml元素映射到c#属性的映射是什么?

    mySection   ConfigurationSection
    item Type   ConfigurationElement
    

    xml属性到c#属性的映射是什么?

    id      ConfigurationProperty 
    data    ConfigurationProperty
    item1   ConfigurationProperty
    item2   ConfigurationProperty
    

    如何为类型“myType”声明类?

    public class myType : ConfigurationSection {
    

    如何声明一个简单的属性'id'?

    //Inside myType as
    [ConfigurationProperty("id", IsRequired = false)]
    public string Id {
        get { return (string)this["id"];  }
        set { this["id"]=value;}
    }
    

    如何声明item元素的类型?

    //Inside myType as a sub class
    public class myTypeElement : ConfigurationElement {
           [ConfigurationProperty("data", IsRequired = false)]
           public string Data {
                get { return (string)this["data"];  }
                set { this["data"]=value;}
            }
    }
    

    如何声明item元素?

    [ConfigurationProperty("item1)]
    public myTypeElement Item1{
            get { return (myTypeElement)this["item1"] }
            set { this["item1"]=value;}
    }
    

    如何从组名“mySection”访问这些?

    Sample.myType t = (Sample.myType)System.Configuration.ConfigurationManager.GetSection("mySection");
    string s = t.item1.data;
    

    这在 MSDN 和其他人的什么地方?

    如何:使用 ConfigurationSection 创建自定义配置部分

    msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx

    blog.danskingdom.com/adding-and-accessing-custom-sections-in-your-c-app-config/

    【讨论】:

      猜你喜欢
      • 2010-11-21
      • 2011-10-02
      • 2015-01-05
      • 2016-05-02
      • 2011-11-21
      • 1970-01-01
      • 2012-10-04
      • 2011-12-10
      相关资源
      最近更新 更多