.NETカスタム構成セット

3204 ワード

直接コード:
    public class MySection : ConfigurationSection
    {
        private const String collectionProertyName = ""; //  ConfigurationProperty  , 

        [ConfigurationProperty(collectionProertyName, Options = ConfigurationPropertyOptions.IsDefaultCollection)]
        public MySettingsCollection MySettings
        {
            get
            {
                return (MySettingsCollection)base[collectionProertyName];
            }
        }

        public static MySection Section
        {
            get
            {
                MySection section = ConfigurationManager.GetSection("mySettings") as MySection;

                if ((section == null))
                {
                    throw new ConfigurationErrorsException(" ");
                }

                return section;
            }
        }

        
    }

    public class MySettings : ConfigurationElement
    {
        [ConfigurationProperty("key", Options = ConfigurationPropertyOptions.IsKey | ConfigurationPropertyOptions.IsRequired)] // IsKey
        public String Key
        {
            get { return (String)base["key"]; }
            set { base["key"] = value; }
        }

        [ConfigurationProperty("value1")]  // 
        public Decimal Value1
        {
            get { return (Decimal)base["value1"]; }
            set { base["value1"] = value; }
        }

        [ConfigurationProperty("value2")]
        public Decimal Value2
        {
            get { return (Decimal)base["value2"]; }
            set { base["value2"] = value; }
        }
    }

    public class MySettingsCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new MySettings();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MySettings)element).Key; // Key Options IsKey, 
        }

        public MySettings this[String Key]
        {
            get { return (MySettings)BaseGet(Key); }
        }
    }

以上はコードで、以下は構成です.
<configuration>
 <configSections>
  <!--type="Study.SystemConfiratuion.MySection,Study" Study.SystemConfiratuion.MySection ;Study  -->
  <section name="mySettings" type="Study.SystemConfiratuion.MySection,Study"/>
 </configSections>
 <mySettings>
  <add key="test1" value1="11" value2="12"></add>
  <add key="test2" value1="21" value2="22"></add>
 </mySettings>
</configuration>

テストコードは次のとおりです.
[Test] // 
        public void Test()
        {
            var settings = MySection.Section.MySettings;
            Assert.AreEqual(11,settings["test1"].Value1);
            Assert.AreEqual(12, settings["test1"].Value2);

            Assert.AreEqual(21, settings["test2"].Value1);
            Assert.AreEqual(22, settings["test2"].Value2);
        }