Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从ConfigurationPropertyAttribute获取ConfigurationElementCollection中的密钥?_C#_Configuration_Configurationmanager - Fatal编程技术网

C# 从ConfigurationPropertyAttribute获取ConfigurationElementCollection中的密钥?

C# 从ConfigurationPropertyAttribute获取ConfigurationElementCollection中的密钥?,c#,configuration,configurationmanager,C#,Configuration,Configurationmanager,有很多例子解释了如何创建自己的ConfigurationElementCollection,例如: 必须重写的函数之一是GetElementKey: protected override object GetElementKey(ConfigurationElement element) { return ((ServiceConfig) element).Port; } 其中,属性端口定义如下: [ConfigurationProperty("Port", IsRequired = tr

有很多例子解释了如何创建自己的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获取密钥属性?

代码如下:

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;
     }
公共类ConfigCollection:ConfigurationElementCollection其中T:ConfigurationElement,new()
{
受保护的覆盖对象GetElementKey(ConfigurationElement元素)
{
//获取IsKey=true的属性的propertyInfo
PropertyInfo键PropertyInfo=。。。
对象keyValue=keyPropertyInfo.GetValue(元素);
返回键值;
}

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

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;
}
受保护的覆盖对象GetElementKey(ConfigurationElement)
{
object key=element.GetType()
.GetProperties()
.Where(p=>p.GetCustomAttributes()
.Any(a=>a.IsKey))
.Select(p=>p.GetValue(元素))
.FirstOrDefault();
返回键;
}