【问题标题】:What is "Configuration Type"?什么是“配置类型”?
【发布时间】:2011-09-21 12:28:28
【问题描述】:

我在与配置文件交互方面没有太多经验,我正在阅读 MSDN 中的 GetSection() 方法,其中指出:

**Notes to Implementers**: 

    You must cast the return value to the expected configuration type. 
To avoid possible casting exceptions, you should use a conditional 
casting operation such as... 

本说明中的“配置类型”是什么意思?选择的部分不是总是代表一个 xml 节点吗?

【问题讨论】:

    标签: .net xml xpath configuration-files


    【解决方案1】:

    Configuration Type 基本上只是您定义的自定义类的类型,用于表示您要存储在 App.Config 或 Web.Config 中的配置值

    您的自定义配置部分需要从System.Configuration.ConfigurationSection 继承,并且当您使用GetSection 方法时,您需要将返回值转换为您从System.Configuration.ConfigurationSection 继承的自定义类的类型

    查看更多here

    如果我有一个特殊的类来表示我想存储在 App.Config 或 Web.Config 中的属性,例如:

    public class MyConfig : ConfigurationSection
    {
        [ConfigurationProperty("myConfigProp", DefaultValue = "false", IsRequired = false)]
        public Boolean MyConfigProp
        {
            get
            { 
                return (Boolean)this["myConfigProp"]; 
            }
            set
            { 
                this["myConfigProp"] = value; 
            }
        }
    }
    

    任何时候我想访问该属性,我都会在我的代码中执行以下操作:

    //create a MyConfig object from the XML in my App.Config file
    MyConfig config = (MyConfig)System.Configuration.ConfigurationManager.GetSection("myConfig");
    
    //access the MyConfigProp property
    bool test = config.MyConfigProp;
    

    【讨论】:

      【解决方案2】:

      MSDN 上有一些很棒的示例:http://msdn.microsoft.com/en-us/library/2tw134k3.aspx

      这里,“配置类型”是为扩展ConfigurationSection 而创建的自定义类型。是的,这是作为一个 XML 节点实现的,但是 System.Configuration 命名空间的意图是把它抽象出来。

      【讨论】:

        猜你喜欢
        • 2020-12-06
        • 2021-05-10
        • 1970-01-01
        • 2020-07-14
        • 1970-01-01
        • 1970-01-01
        • 2016-08-26
        • 1970-01-01
        • 2020-01-11
        相关资源
        最近更新 更多