Riflessione e proprietà complesse
-
27-10-2019 - |
Domanda
Ho un oggetto con proprietà primitive e complesse.
Devo ottenere i valori delle proprietà riflettendo.
Utilizzo queste affermazioni:
Dim propertyInfo As PropertyInfo = MYITEM.GetType().GetProperty("MyProp1")
Dim propertyValue As Object = propertyInfo.GetValue(MYITEM, Nothing)
e va bene, ma se utilizzo lo stesso codice con proprietà complesse come questa...
Dim propertyInfo As PropertyInfo = MYITEM.GetType().GetProperty("MyProp1.MyProp2")
Dim propertyValue As Object = propertyInfo.GetValue(MYITEM, Nothing)
propertyInfo è null e non riesco a leggere il valore di "MyProp2".
Esiste un metodo generico per farlo?
Soluzione
MyProp1.MyProp2 non è una proprietà del tuo oggetto base, MyProp1 è una proprietà di quella quindi MyProp2 è una proprietà dell'oggetto restituito da MyProp1.
Prova questo :
Dim propertyInfo1 As PropertyInfo = MYITEM.GetType().GetProperty("MyProp1")
Dim propertyValue1 As Object = propertyInfo.GetValue(MYITEM, Nothing)
Dim propertyInfo2 As PropertyInfo = propertyValue1.GetType().GetProperty("MyProp2")
Dim propertyValue2 As Object = propertyInfo2.GetValue(propertyValue1, Nothing)
Potresti provare qualcosa come questo metodo di estensione (scusate è in c#)
public static TRet GetPropertyValue<TRet>(this object obj, string propertyPathName)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
string[] parts = propertyPathName.Split('.');
string path = propertyPathName;
object root = obj;
if (parts.Length > 1)
{
path = parts[parts.Length - 1];
parts = parts.TakeWhile((p, i) => i < parts.Length-1).ToArray();
string path2 = String.Join(".", parts);
root = obj.GetPropertyValue<object>(path2);
}
var sourceType = root.GetType();
return (TRet)sourceType.GetProperty(path).GetValue(root, null);
}
Quindi per testare
public class Test1
{
public Test1()
{
this.Prop1 = new Test2();
}
public Test2 Prop1 { get; set; }
}
public class Test2
{
public Test2()
{
this.Prop2 = new Test3();
}
public Test3 Prop2 { get; set; }
}
public class Test3
{
public Test3()
{
this.Prop3 = DateTime.Now.AddDays(-1); // Yesterday
}
public DateTime Prop3 { get; set; }
}
Utilizzo
Test1 obj = new Test1();
var yesterday = obj.GetPropertyValue<DateTime>("Prop1.Prop2.Prop3");
Altri suggerimenti
Se sei in un progetto web o non ti dispiace fare riferimento a System.Web, potresti utilizzare:
object resolvedValue = DataBinder.Eval(object o, string propertyPath);
Che è più semplice ed è già stato testato da Microsoft