Set object property using reflection

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

    You can also access fields using a simillar manner:

    var obj=new MyObject();
    FieldInfo fi = obj.GetType().
      GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
    fi.SetValue(obj,value)
    

    With reflection everything can be an open book:) In my example we are binding to a private instance level field.

提交回复
热议问题