Set object property using reflection

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

    You can also do:

    Type type = target.GetType();
    
    PropertyInfo prop = type.GetProperty("propertyName");
    
    prop.SetValue (target, propertyValue, null);
    

    where target is the object that will have its property set.

提交回复
热议问题