2016-02-08 1 views
0

Il y a beaucoup d'exemples là-bas qui expliquent comment créer votre propre ConfigurationElementCollection, par exemple: Stackoverflow: How to implement your own ConfigurationElementCollection?GetKey dans ConfigurationElementCollection à partir de ConfigurationPropertyAttribute?

L'une des fonctions que vous aurez à passer outre est GetElementKey:

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

où la propriété Port est défini comme suit:

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

Ma configuration a plusieurs ConfigurationElementCollections qui semblent très similaires. La fonction GetElementKey est la seule fonction qui empêche l'utilisation d'un ConfigurationElementCollection générique en raison de l'identifiant de la clé. Le ConfigurationPropertyAttribute m'informe déjà quelle propriété est la clé.

Est-il possible d'obtenir la propriété Key via ConfigurationPropertyAttribute?

code serait comme:

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

Répondre

0

Oui, vous pouvez obtenir toutes les propriétés de l'élément et chercher celui qui a un ConfigurationPropertyAttribute avec 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; 
}