.net 反射与复合性质
我有一个具有原始和复杂属性的对象 我必须通过反射得到属性值 我使用以下语句:.net 反射与复合性质,.net,reflection,properties,propertyinfo,.net,Reflection,Properties,Propertyinfo,我有一个具有原始和复杂属性的对象 我必须通过反射得到属性值 我使用以下语句: Dim propertyInfo As PropertyInfo = MYITEM.GetType().GetProperty("MyProp1") Dim propertyValue As Object = propertyInfo.GetValue(MYITEM, Nothing) 这没关系,但如果我用同样的代码来处理像这样复杂的属性 Dim propertyInfo As PropertyInfo = MYIT
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#)
用法
test1obj=newtest1();
var Dayed=obj.GetPropertyValue(“Prop1.Prop2.Prop3”);
如果您在web项目中,或者不介意引用System.web,您可以使用:
object resolvedValue = DataBinder.Eval(object o, string propertyPath);
它更简单,并且已经被微软测试过了,对吧,但是为了直接读取对象属性值,我必须推广这个机制。有可能吗?太好了。它起作用了。。。我已经用同样的逻辑写了一个方法,但是你的版本更优雅。谢谢
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");
object resolvedValue = DataBinder.Eval(object o, string propertyPath);