Set object property using reflection

后端 未结 10 1685
终归单人心
终归单人心 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:17

    Reflection, basically, i.e.

    myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
    

    or there are libraries to help both in terms of convenience and performance; for example with FastMember:

    var wrapped = ObjectAccessor.Create(obj); 
    wrapped[property] = "Bob";
    

    (which also has the advantage of not needing to know in advance whether it is a field vs a property)

提交回复
热议问题