Set object property using reflection

后端 未结 10 1663
终归单人心
终归单人心 2020-11-21 23:22

Is there a way in C# where I can use reflection to set an object property?

Ex:

MyObject obj = new MyObject();
obj.Name = \"Value\";

10条回答
  •  渐次进展
    2020-11-22 00:09

    I have just published a Nuget package that allows setting up not only the first level Properties but also nested properties in the given object in any depth.

    Here is the package

    Sets the value of a property of an object by its path from the root.

    The object can be a complex object and the property can be multi level deep nested property or it can be a property directly under the root. ObjectWriter will find the property using the property path parameter and update its value. Property path is the appended names of the properties visited from root to the end node property which we want to set, delimited by the delimiter string parameter.

    Usage:

    For setting up the properties directly under the object root:

    Ie. LineItem class has an int property called ItemId

    LineItem lineItem = new LineItem();
    
    ObjectWriter.Set(lineItem, "ItemId", 13, delimiter: null);
    

    For setting up nested property multiple levels below the object root:

    Ie. Invite class has a property called State, which has a property called Invite (of Invite type), which has a property called Recipient, which has a property called Id.

    To make things even more complex, the State property is not a reference type, it is a struct.

    Here is how you can set the Id property (to string value of “outlook”) at the bottom of the object tree in a single line.

    Invite invite = new Invite();
    
    ObjectWriter.Set(invite, "State_Invite_Recipient_Id", "outlook", delimiter: "_");
    

提交回复
热议问题