簡體   English   中英

System.Reflection 獲取屬性為 object 並設置該屬性的另一個屬性

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

因此,在我的項目中,在 STL 文件中,有一些點,當我移動一個點時,坐標信息會發生變化。 當一個點移動時,它必須被標記為已修改。

當我移動點時,我有點的屬性名稱。 從屬性名稱中,我可以訪問該屬性,它返回一個 Custom3DPoint。

Custom3DPoint class 具有 Status 屬性。

為了更清楚地解釋,我有一個名為 A 的 class,它有兩個屬性 P1 和 P2。 我還有另一個名為 B 的 class 具有 A 類型的屬性。

如何從propertyname P1獲取object B的property並設置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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM