Set object property using reflection

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

    Use somethings like this :

    public static class PropertyExtension{       
    
       public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
       {
        PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
        property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
       }
    }
    

    or

    public static class PropertyExtension{       
    
       public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
       {
        PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
        Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
        object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
    
        property.SetValue(p_object, safeValue, null);
       }
    }
    

提交回复
热议问题