4

我有一个具有原始和复杂属性的对象。

我必须通过反射来获取属性值。

我使用以下语句:

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 为空,我无法读取“MyProp2”的值。

是否存在执行此操作的通用方法?

4

2 回答 2

7

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");
于 2011-01-31T10:04:46.850 回答
0

如果你在一个 web 项目中,或者不介意引用 System.Web,你可以使用:

object resolvedValue = DataBinder.Eval(object o, string propertyPath);

哪个更简单,并且已经被微软测试过

于 2011-12-13T05:18:27.203 回答