System.Reflection 获取 属性 作为对象并设置 属性 的另一个 属性

System.Reflection Get property as an object and set another property of the property

所以,在我的项目中,在一个STL文件中,有一些点,当我移动一个点时,坐标信息会改变。当一个点移动时,它必须被标记为已修改。

当我移动点时,我有点的 属性 名称。从 属性 名称,我可以访问 属性,它 returns 一个 Custom3DPoint。

Custom3DPoint class 具有状态 属性。

为了更清楚的解释,我有一个名为 A 的 class,它有两个属性 P1 和 P2。我还有另一个名为 B 的 class,它有一个 属性 类型的 A.

如何从属性名称P1获取对象B的属性并设置P2值。

这是我尝试过的:

class A
{
    public string P1{ get; set; }
    public string P2 { get; set; }

    public A()
    {
        P1 = "value1";
        P2 = "value2";
    }
}

class B
{
    public A PropA { get; set; }
    public B()
    {
        PropA = new test.A();

    }
}

void Moved(B obj, string propertyName)
{
    var prop = obj.GetType().GetProperty(propertyName);
    var statusProp = prop.GetType().GetProperty("Status"); //this line returns null because

    prop.GetType().GetProperties(); // doesn't return properties of A object.

    statusProp.SetValue(prop, "modified");
}

是否可以使用反射?

您需要获取 属性 的值,然后更改内部属性:

void Moved(B obj, string propertyName)
{
    // get property of B object
    var prop = obj.GetType().GetProperty("PropA");
    // get value of B.PropA
    var aValue = prop.GetValue(obj);
    // get property of A object
    var aProp = aValue.GetType().GetProperty(propertyName);
    // change property in A object
    aProp.SetValue(aValue, "modified");
}