在c#中是否有一种方法,我可以使用反射来设置对象属性?

Ex:

MyObject obj = new MyObject();
obj.Name = "Value";

我要设置obj。带有反射的名称。喜欢的东西:

Reflection.SetProperty(obj, "Name") = "Value";

有什么办法可以做到吗?


当前回答

你也可以使用类似的方式访问字段:

var obj=new MyObject();
FieldInfo fi = obj.GetType().
  GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)

在我的例子中,我们绑定到一个私有实例级字段。

其他回答

或者你可以在你自己的扩展类中包装Marc的一行代码:

public static class PropertyExtension{       

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

像这样叫它:

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

为了更好地衡量,让我们添加一个方法来获取属性值:

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

是的,你可以使用type . invokember ():

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

如果obj没有名为Name的属性,或者它无法设置,这将抛出异常。

另一种方法是获取属性的元数据,然后对其进行设置。这将允许你检查属性是否存在,并验证它是否可以被设置:

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);
}

反射,基本上就是。

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

或者有库在便利性和性能方面提供帮助;例如FastMember:

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

(这也有一个优点,不需要提前知道它是一个字段还是一个属性)

当你想使用属性名从另一个对象批量分配一个对象的属性时,你可以尝试一下:

public static void Assign(this object destination, object source)
    {
        if (destination is IEnumerable && source is IEnumerable)
        {
            var dest_enumerator = (destination as IEnumerable).GetEnumerator();
            var src_enumerator = (source as IEnumerable).GetEnumerator();
            while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
                dest_enumerator.Current.Assign(src_enumerator.Current);
        }
        else
        {
            var destProperties = destination.GetType().GetProperties();
            foreach (var sourceProperty in source.GetType().GetProperties())
            {
                foreach (var destProperty in destProperties)
                {
                    if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
                    {
                        destProperty.SetValue(destination,     sourceProperty.GetValue(source, new object[] { }), new object[] { });
                        break;
            }
        }
    }
}

你还可以:

Type type = target.GetType();

PropertyInfo prop = type.GetProperty("propertyName");

prop.SetValue (target, propertyValue, null);

其中target是将设置其属性的对象。