-
27-10-2019 - |
質問
原始的で複雑な特性を持つオブジェクトがあります。
反射によってプロパティ値を取得する必要があります。
私はこのステートメントを使用します:
Dim propertyInfo As PropertyInfo = MYITEM.GetType().GetProperty("MyProp1")
Dim propertyValue As Object = propertyInfo.GetValue(MYITEM, Nothing)
そして、それは「しかし、私がこのような複雑なプロパティを持つ同じコードを使用する場合...
Dim propertyInfo As PropertyInfo = MYITEM.GetType().GetProperty("MyProp1.MyProp2")
Dim propertyValue As Object = propertyInfo.GetValue(MYITEM, Nothing)
PropertyInfoはnullで、「myprop2」の値を読むことができません。
これを行うための一般的な方法はありますか?
解決
myProp1.myprop2はベースオブジェクトのプロパティではなく、myprop1はそのプロパティであり、myprop2はmyprop1によって返されるオブジェクトのプロパティです。
これを試して :
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)
この拡張メソッドのようなものを試すことができます(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);
}
その後、テストします
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; }
}
使用法
Test1 obj = new Test1();
var yesterday = obj.GetPropertyValue<DateTime>("Prop1.Prop2.Prop3");
他のヒント
Webプロジェクトに参加している場合、または参照System.WEBを気にしないでください。使用できます。
object resolvedValue = DataBinder.Eval(object o, string propertyPath);
これはよりシンプルで、すでにMicrosoftによってテストされています
所属していません StackOverflow