【发布时间】:2016-05-17 22:03:50
【问题描述】:
有很多示例可以解释如何创建自己的 ConfigurationElementCollection,例如:Stackoverflow: How to implement your own ConfigurationElementCollection?
您必须重写的函数之一是 GetElementKey:
protected override object GetElementKey(ConfigurationElement element)
{
return ((ServiceConfig) element).Port;
}
其中属性Port定义如下:
[ConfigurationProperty("Port", IsRequired = true, IsKey = true)]
public int Port
{
get { return (int) this["Port"]; }
set { this["Port"] = value; }
}
我的配置有几个看起来非常相似的 ConfigurationElementCollections。 GetElementKey 函数是唯一一个由于键的标识符而禁止使用通用 ConfigurationElementCollection 的函数。 ConfigurationPropertyAttribute 已经告诉我哪个属性是关键。
是否可以通过 ConfigurationPropertyAttribute 获取 Key 属性?
代码如下:
public class ConfigCollection<T> : ConfigurationElementCollection where T: ConfigurationElement, new()
{
protected override Object GetElementKey(ConfigurationElement element)
{
// get the propertyInfo of property that has IsKey = true
PropertyInfo keyPropertyInfo = ...
object keyValue = keyPropertyInfo.GetValue(element);
return keyValue;
}
【问题讨论】:
标签: c# configuration configurationmanager