GetKey in ConfigurationElementCollection from ConfigurationP



有很多例子可以解释如何创建自己的ConfigurationElementCollection,例如:Stackoverflow:如何实现自己的ConfigurationElementCollection?

您必须覆盖的函数之一是GetElementKey:

protected override object GetElementKey(ConfigurationElement element)
{
  return ((ServiceConfig) element).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;
     }

是的,您可以获取元素的所有属性并查找具有ConfigurationPropertyAttribute的元素 IsKey == true

protected override object GetElementKey(ConfigurationElement element)
{
    object key = element.GetType()
                        .GetProperties()
                        .Where(p => p.GetCustomAttributes<ConfigurationPropertyAttribute>()
                                     .Any(a => a.IsKey))
                        .Select(p => p.GetValue(element))
                        .FirstOrDefault();
    return key;
}

最新更新