【问题标题】:GetKey in ConfigurationElementCollection from ConfigurationPropertyAttribute?从 ConfigurationPropertyAttribute 获取 ConfigurationElementCollection 中的键?
【发布时间】: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


    【解决方案1】:

    是的,您可以获取元素的所有属性并查找具有ConfigurationPropertyAttributeIsKey == 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 2010-12-10
      相关资源
      最近更新 更多