我希望在web.config中有一个自定义部分,如下所示:
<MyMainSection attributeForMainSection = "value foo">
<add name = "foo"
type = "The.System.Type.Of.Foo, Assembly, Qualified Name Type Name" />
<add name = "bar"
type = "The.System.Type.Of.Bar, Assembly, Qualified Name Type Name" />
</MyMainSection>
我已经定义了以下代码:
using System.Configuration;
class MyMainSection : ConfigurationSection
{
/*I've provided custom implemenation.
Not including it here for the sake of brevity. */
[ConfigurationProperty("attributeForMainSection")]
public string AttributeForMyMainSection { get; set; }
[ConfigurationProperty("add")]
public AddElement TheAddElement { get; set; }
private class AddElement: ConfigurationElement
{
/* Implementation done */
}
}
如果我想允许多个添加元素,此属性TheAddElement
应该是IEnumerable<AddElement>
还是仅AddElement
?
答案 0 :(得分:13)
两者都没有,你会引入新的ConfigurationCollectionElement而不是像<。p>
栏目强>
class MyMainSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired=true, IsDefaultCollection=true)]
public AddElementCollection Instances
{
get { return (AddElementCollection) this[""]; }
set { this[""] = value; }
}
}
<强>集合强>
public class AddElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new AddElement();
}
protected override object GetElementKey(ConfigurationElement element) {
return ((AddElement) element).Name;
}
}
<强>元素强>
private class AddElement: ConfigurationElement
{
[ConfigurationProperty("name", IsKey=true, IsRequired=true)]
public string Name
{
get { return (string) base["name"]; }
set { base["name"] = value;
}
...
}
答案 1 :(得分:4)
使用ConfigurationElementCollection处理ConfigurationElement对象的集合。实现此类以将自定义ConfigurationElement元素的集合添加到ConfigurationSection:
// Define a custom section that contains a custom
// UrlsCollection collection of custom UrlConfigElement elements.
// This class shows how to use the ConfigurationCollectionAttribute.
public class UrlsSection : ConfigurationSection
{
// Declare the Urls collection property using the
// ConfigurationCollectionAttribute.
// This allows to build a nested section that contains
// a collection of elements.
[ConfigurationProperty("urls", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(UrlsCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public UrlsCollection Urls
{
get
{
UrlsCollection urlsCollection =
(UrlsCollection)base["urls"];
return urlsCollection;
}
}
}
// Define the custom UrlsCollection that contains the
// custom UrlsConfigElement elements.
public class UrlsCollection : ConfigurationElementCollection
{
// ...
http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx