C# 从ConfigurationPropertyAttribute获取ConfigurationElementCollection中的密钥?
有很多例子解释了如何创建自己的ConfigurationElementCollection,例如: 必须重写的函数之一是GetElementKey: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
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();
返回键;
}