mardi 19 janvier 2021

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

So, in my project, on a STL file, there are some points, when I move a point, the coordinate informations change. When a point moved, it must be marked as modified.

And when I move the point, I have the property name of the point. From the property name, I can access to the property, it returns a Custom3DPoint.

The Custom3DPoint class has a Status property.

For a clearer explanation, I have a class named A which has two properties P1 and P2. And I have another class named B which has a property of type A.

How to get the property of the object B from the propertyname P1 and set the P2 value.

Here is what I tried :

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");
}

Is it possible using Reflection ?





Aucun commentaire:

Enregistrer un commentaire