Set object property using reflection

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

    Or you could wrap Marc's one liner inside your own extension class:

    public static class PropertyExtension{       
    
       public static void SetPropertyValue(this object obj, string propName, object value)
        {
            obj.GetType().GetProperty(propName).SetValue(obj, value, null);
        }
    }
    

    and call it like this:

    myObject.SetPropertyValue("myProperty", "myValue");
    

    For good measure, let's add a method to get a property value:

    public static object GetPropertyValue(this object obj, string propName)
    {
            return obj.GetType().GetProperty(propName).GetValue (obj, null);
    }
    

提交回复
热议问题