Je voulais savoir comment obtenir la valeur de la propriété en C#, mais cette propriété est d'un autre type.C# Réflexion sur les propriétés imbriquées d'une classe
public class Customer
{
public string Name {get; set;}
public string Lastname {get; set;}
public CustomerAddress Address {get; set;}
}
Je suis en mesure d'obtenir les valeurs de propriété de nom et LastName mais je ne reçoivent pas tout à fait comment obtenir la valeur de CustomerAddress.City.
C'est ce que j'ai jusqu'à maintenant.
public object GetPropertyValue(object obj, string property)
{
if (string.IsNullOrEmpty(property))
return new object { };
PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}
Ensuite, utilisez cette méthode dans une instruction LINQ.
var cells = (from m in model
select new
{
i = GetPropertyValue(m, key),
cell = from c in columns
select reflection.GetPropertyValue(m, c)
}).ToArray();
Je n'ai donc aucune valeur pour CustomerAddress.
Toute aide sera grandement appréciée.
**** **** MISE A JOUR
Voici comment je réussi à le faire.
public object GetNestedPropertyValue(object obj, string property)
{
if (string.IsNullOrEmpty(property))
return string.Empty;
var propertyNames = property.Split('.');
foreach (var p in propertyNames)
{
if (obj == null)
return string.Empty;
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(p);
if (info == null)
return string.Empty;
obj = info.GetValue(obj, null);
}
return obj;
}
Que diriez-vous de définir la valeur d'une propriété nichée? (Même que celui-ci, mais pour info.SetValue ...)? – Denis