在 ConfigurationSection 增加 ConfigurationElement 的做法
不具彈性,單純為了進一步了解 ConfigurationElement 的使用
方案架構如同上個範例:組態檔 ConfigSection 的使用
此範例在 ConfigSection 內加上一個 ConfigurationElement
如需多個 ConfigurationElement 必須逐一宣告,並且名稱都要不一樣
註:如果要讓 ConfigurationElement 變成 集合的方式使用,就必須套用 ConfigurationElementCollection才可以
其他使用方式如同 Section 一樣
ConfigurationDemo中的 App.config 內容如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Demo1" type="ConfigurationDemo.LibData.DemoSection, LibData" />
<section name="Demo2" type="ConfigurationDemo.LibData.DemoSection, LibData" />
<section name="Demo3" type="ConfigurationDemo.LibData.DemoSection, LibData" />
</configSections>
<Demo1 ID="1" Name="本機" >
<domain url="localhost" />
</Demo1>
<Demo2 ID="2" Name="測試機" >
<domain url="test.com" />
</Demo2>
<Demo3 ID="3" Name="正式機" >
<domain url="demo.com" />
</Demo3>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
LibData 內容為:
using System.Configuration;
namespace ConfigurationDemo.LibData
{
public class DemoSection : ConfigurationSection
{
[ConfigurationProperty("ID")]
public int ID
{
get { return (int)this["ID"]; }
}
[ConfigurationProperty("Name")]
public string Name
{
get { return (string)this["Name"]; }
}
[ConfigurationProperty("domain")]
public DomainElement Domain
{
get { return this["domain"] as DomainElement; }
}
}
public class DomainElement : ConfigurationElement
{
[ConfigurationProperty("url")]
public string Url
{
get { return this["url"] as string; }
}
}
}
ConfigurationDemo > Program.cs 執行程式的語法 如下:
using ConfigurationDemo.LibData;
using System;
using System.Configuration;
namespace ConfigurationDemo
{
class Program
{
static void Main(string[] args)
{
DemoSection ds1 = ConfigurationManager.GetSection("Demo1") as DemoSection;
PrintSiteSection(ds1);
Console.WriteLine();
DemoSection ds2 = ConfigurationManager.GetSection("Demo2") as DemoSection;
PrintSiteSection(ds2);
Console.WriteLine();
DemoSection ds3 = ConfigurationManager.GetSection("Demo3") as DemoSection;
PrintSiteSection(ds3);
Console.ReadLine();
}
public static void PrintSiteSection(DemoSection section)
{
Console.WriteLine($"SectionName:{section.SectionInformation.Name}\tid:{section.ID}\tname:{section.Name}");
Console.WriteLine("└ElementName:" + nameof(section.Domain));
PrintDomainElement(section.Domain);
}
public static void PrintDomainElement(DomainElement element)
{
Console.WriteLine($" └─Url:{element.Url}");
}
}
}
執行結果: