Voici un code que j'utilise pour obtenir l'état initial de toutes les propriétés publiques dans une classe pour la vérification IsDirty.Comment savoir si un PropertyInfo est une collection
Quel est le moyen le plus simple de voir si une propriété est IEnumerable?
Cheers,
Berryl
protected virtual Dictionary<string, object> _GetPropertyValues()
{
return _getPublicPropertiesWithSetters()
.ToDictionary(pi => pi.Name, pi => pi.GetValue(this, null));
}
private IEnumerable<PropertyInfo> _getPublicPropertiesWithSetters()
{
return GetType().GetProperties().Where(pi => pi.CanWrite);
}
MISE À JOUR
Ce que je blesse faire est d'ajouter quelques extensions de bibliothèque comme suit
public static bool IsNonStringEnumerable(this PropertyInfo pi) {
return pi != null && pi.PropertyType.IsNonStringEnumerable();
}
public static bool IsNonStringEnumerable(this object instance) {
return instance != null && instance.GetType().IsNonStringEnumerable();
}
public static bool IsNonStringEnumerable(this Type type) {
if (type == null || type == typeof(string))
return false;
return typeof(IEnumerable).IsAssignableFrom(type);
}
Notez qu'une chaîne est un IEnumerable trop –
Il résout le problème http://stackoverflow.com/a/40376537/5996253 –