简体   繁体   English

从ConfigurationPropertyAttribute中获取ConfigurationElementCollection中的GetKey?

[英]GetKey in ConfigurationElementCollection from ConfigurationPropertyAttribute?

There are a lot of examples out there that explain how to create your own ConfigurationElementCollection, for instance: Stackoverflow: How to implement your own ConfigurationElementCollection? 有很多示例可以解释如何创建自己的ConfigurationElementCollection,例如: Stackoverflow:如何实现自己的ConfigurationElementCollection?

One of the functions you'll have to override is GetElementKey: 您必须重写的功能之一是GetElementKey:

protected override object GetElementKey(ConfigurationElement element)
{
  return ((ServiceConfig) element).Port;
}

where property Port is defined as follows: 其中属性端口定义如下:

[ConfigurationProperty("Port", IsRequired = true, IsKey = true)]
public int Port 
{
  get { return (int) this["Port"]; }
  set { this["Port"] = value; }
}

My configuration has several ConfigurationElementCollections that look very similar. 我的配置有几个看起来非常相似的ConfigurationElementCollections。 The GetElementKey function is the only function that inhibits the use of a generic ConfigurationElementCollection because of the identifier of the key. 由于键的标识符,GetElementKey函数是唯一一个禁止使用通用ConfigurationElementCollection的函数。 The ConfigurationPropertyAttribute already informs me which property is the key. ConfigurationPropertyAttribute已经通知我哪个属性是关键。

Is it possible to get the Key property via the ConfigurationPropertyAttribute? 是否可以通过ConfigurationPropertyAttribute获取Key属性?

Code would be like: 代码如下:

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;
     }

Yes, you can get all the properties of the element and look for the one that has a ConfigurationPropertyAttribute with IsKey == true : 是的,您可以获取元素的所有属性,并查找具有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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM