Tôi có các phần cấu hình tùy chỉnh của riêng mình nhưng muốn tạo một phần tử mới có khóa/giá trị đơn giản bên trong nó. Bây giờ tôi có một phiên bản làm việc nhưng có vẻ như khá nhiều mã cho một nhiệm vụ đơn giản như vậy. Có cách cải tiến để làm mọi thứ không?Cách xác định phần cấu hình tùy chỉnh cơ bản?
Dưới đây là phiên bản rút gọn của cấu hình và lớp cấu hình tùy chỉnh của tôi.
web.config
<myRootNode>
<myNode>
<add key="a" value="" />
<add key="b" value="" />
<add key="c" value="" />
...
</myNode>
...any other nodes
</myRootNode>
Tuỳ chỉnh cấu hình lớp
public class MyRootNode : ConfigurationSection
{
[ConfigurationProperty("myNode")]
public MyNodeElement MyNode
{
get { return (MyNodeElement)this["myNode"]; }
}
}
[ConfigurationCollection(typeof(BaseElement), AddItemName = "add")]
public class MyNodeElement : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new BaseElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((BaseElement)element).Key;
}
public BaseElement this[int index]
{
get { return this.BaseGet(index) as BaseElement; }
}
}
public class BaseElement : ConfigurationElement
{
[ConfigurationProperty("key", IsRequired = true, IsKey = true)]
public string Key
{
get { return this["key"].ToString(); }
}
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return this["value"].ToString(); }
}
}
Hãy thử bài viết này: [Viết phần Cài đặt cấu hình tùy chỉnh trong C#] (http://www.codearsenal.net/2012/10/writing-custom-configuration-section-in-csharp.html) –