Set object property using reflection

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

    Yes, using System.Reflection:

    using System.Reflection;
    
    ...
    
        string prop = "name";
        PropertyInfo pi = myObject.GetType().GetProperty(prop);
        pi.SetValue(myObject, "Bob", null);
    

提交回复
热议问题