OrderElement.cs:
1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.Linq; 5 using System.Text; 6 7 namespace TestSection.SectionClass 8 { 9 public class OrderElement : ConfigurationElement10 {11 [ConfigurationProperty("number")]12 public string Number13 {14 get15 {16 return (string)base["number"];17 }18 set19 {20 base["number"] = value;21 }22 }23 24 [ConfigurationProperty("amount", IsRequired = true)]25 public double Amount26 {27 get28 {29 return (double)base["amount"];30 }31 set32 {33 base["amount"] = value;34 }35 }36 }37 }
OrderElementColletion.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.Linq; 5 using System.Text; 6 7 namespace TestSection.SectionClass 8 { 9 public class OrderElementColletion : ConfigurationElementCollection10 {11 protected override ConfigurationElement CreateNewElement()12 {13 return new OrderElement();14 }15 16 protected override object GetElementKey(ConfigurationElement element)17 {18 return ((OrderElement)element).Number;19 }20 21 public override ConfigurationElementCollectionType CollectionType22 {23 get24 {25 return ConfigurationElementCollectionType.BasicMap;26 }27 }28 29 protected override string ElementName30 {31 get32 {33 return "order";34 }35 }36 37 public OrderElement this[int index]38 {39 get { return (OrderElement)BaseGet(index); }40 set41 {42 if (BaseGet(index) != null)43 {44 BaseRemoveAt(index);45 }46 BaseAdd(index, value);47 }48 }49 }50 }
OrderSection.cs:
1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.Linq; 5 using System.Text; 6 7 namespace TestSection.SectionClass 8 { 9 public class OrderSection : ConfigurationSection10 {11 [ConfigurationProperty("companyID", IsRequired = true)]12 public String CompanyID13 {14 get15 {16 return (string)base["companyID"];17 }18 set19 {20 base["companyID"] = value;21 }22 }23 24 [ConfigurationProperty("", IsDefaultCollection = true)]25 public OrderElementColletion Orders26 {27 get { return (OrderElementColletion)base[""]; }28 set { base[""] = value; } 29 }30 }31 }
app.config配置方案1:
1 23 4 5 6 78 119 10
引用1:
1 static void Main(string[] args)2 {3 OrderSection config = (OrderSection)ConfigurationManager.GetSection("orders");4 Console.WriteLine(config.CompanyID);5 Console.WriteLine(config.Orders[0].Number);6 Console.WriteLine(config.Orders[0].Amount);7 Console.ReadKey();8 }
app.config配置方案2:
1 23 4 85 6 79 1410 1311 12
引用2:
1 static void Main(string[] args)2 {3 OrderSection config = (OrderSection)ConfigurationManager.GetSection("myGroup/orders");4 Console.WriteLine(config.CompanyID);5 Console.WriteLine(config.Orders[0].Number);6 Console.WriteLine(config.Orders[0].Amount);7 Console.ReadKey();8 }