根据我的app.config,我希望能够获取列的元素,如下面的第 3-5 行示例所示。我应该如何编写代码来实现这一点。如果我需要更改我的 app.config - 我会这样做。
1. var bounceProviders = ConfigurationManager.GetSection("BounceProviders") as BounceProvidersSection;
2. var providerColumns = bounceProviders.Providers[0].Columns;
3. var emailColumn = providerColumns.Email;
4. var dateColumn = providerColumns.Date;
5. var messageColumn = providerColumns.Message;
应用程序配置
<BounceProviders>
<Providers>
<Provider Name="p1">
<Columns>
<Email Name="My Email" />
<Date Name="My Date" />
<Message Name="My Message" />
</Columns>
</Provider>
<Provider Name="p2">
<Columns />
</Provider>
</Providers>
</BounceProviders>
配置部分
public class BounceProvidersSection : ConfigurationSection
{
[ConfigurationCollection(typeof(ConfigCollection<BounceProviderConfig>), AddItemName = "Provider")]
[ConfigurationProperty("Providers", IsRequired = true)]
public ConfigCollection<BounceProviderConfig> Providers
{
get { return (ConfigCollection<BounceProviderConfig>)this["Providers"]; }
set { this["Providers"] = value; }
}
}
public class BounceProviderConfig : ConfigurationElement
{
[ConfigurationProperty("Name", IsRequired = true)]
public string Name
{
get { return (string)this["Name"]; }
set { this["Name"] = value; }
}
}
配置集合
public class ConfigCollection<T> : ConfigurationElementCollection
where T : ConfigurationElement, new()
{
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
protected override object GetElementKey( ConfigurationElement element )
{
return element.GetHashCode();
}
public T this[int index]
{
get
{
return ( T )BaseGet( index );
}
set
{
if ( BaseGet( index ) != null )
{
BaseRemoveAt( index );
}
BaseAdd( index, value );
}
}
new public T this[string Name]
{
get
{
return ( T )BaseGet( Name );
}
}
}
自卫队