Set object property using reflection

后端 未结 10 1480
终归单人心
终归单人心 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);
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • Reflection, basically, i.e.

    myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
    

    or there are libraries to help both in terms of convenience and performance; for example with FastMember:

    var wrapped = ObjectAccessor.Create(obj); 
    wrapped[property] = "Bob";
    

    (which also has the advantage of not needing to know in advance whether it is a field vs a property)

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题