Using reflection to set a property of a property of an object

后端 未结 3 777
一生所求
一生所求 2021-01-12 19:24

I\'ve got two classes.

public class Class1 {
   public string value {get;set;}
}

public class Class2 {
   public Class1 myClass1Object {get;set;}
}
<         


        
3条回答
  •  我在风中等你
    2021-01-12 19:54

    Basically split it into two property accesses. First you get the myClass1Object property, then you set the value property on the result.

    Obviously you'll need to take whatever format you've got the property name in and split it out - e.g. by dots. For example, this should do an arbitrary depth of properties:

    public void SetProperty(object source, string property, object target)
    {
        string[] bits = property.Split('.');
        for (int i=0; i < bits.Length - 1; i++)
        {
             PropertyInfo prop = source.GetType().GetProperty(bits[i]);
             source = prop.GetValue(source, null);
        }
        PropertyInfo propertyToSet = source.GetType()
                                           .GetProperty(bits[bits.Length-1]);
        propertyToSet.SetValue(source, target, null);
    }
    

    Admittedly you'll probably want a bit more error checking than that :)

提交回复
热议问题