Set object property using reflection

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

    Yes, you can use Type.InvokeMember():

    using System.Reflection;
    MyObject obj = new MyObject();
    obj.GetType().InvokeMember("Name",
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
        Type.DefaultBinder, obj, "Value");
    

    This will throw an exception if obj doesn't have a property called Name, or it can't be set.

    Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:

    using System.Reflection;
    MyObject obj = new MyObject();
    PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
    if(null != prop && prop.CanWrite)
    {
        prop.SetValue(obj, "Value", null);
    }
    

提交回复
热议问题