C# 动态设置属性

52

可能是重复问题:
.Net - 使用反射设置对象属性
使用反射设置字符串值的属性

我有一个具有多个属性的对象,我们称之为objName。我想创建一个方法,简单地使用新属性值更新该对象。

我希望在一个方法中能够执行以下操作:

private void SetObjectProperty(string propertyName, string value, ref object objName)
{
    //some processing on the rest of the code to make sure we actually want to set this value.
    objName.propertyName = value
}

最后,调用函数:

SetObjectProperty("nameOfProperty", textBoxValue.Text, ref objName);

希望问题已经充分阐述。如果需要更多细节,请告诉我。

感谢所有的回答!


@DavidArcher 在C#中没有rel键盘...我想你是指ref吧?除非你打算改变它的实际实例,否则没有必要将对象作为ref传递。 - James
确实,我是指ref,并且我确实打算更改实际实例。 - David Archer
5个回答

89

objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)


3
GetProperty() 方法中应使用 propertyName - Anonymous
3
如果 "nameOfProperty" 不存在怎么办? - James
1
当然,你可以使用 GetProperties 进行测试,以捕获异常。 - josejuan
我能够使用你的代码示例用5行代码替换我的200行代码。谢谢,你救了我的一天。 - Ananda

47

你可以使用反射(Reflection)来实现,例如:

private void SetObjectProperty(string propertyName, string value, object obj)
{
    PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);
    // make sure object has the property we are after
    if (propertyInfo != null)
    {
        propertyInfo.SetValue(obj, value, null);
    }
}

4
在调用之前检查是否为null,这个做法值得称赞。 - Chason Arthur
2
我通常也会检查“可写性”:if (propertyInfo != null && propertyInfo.CanWrite) - fdelia
如果我想设置静态属性,该怎么办? - toha

4

首先获取属性信息,然后在属性上设置值:

PropertyInfo propertyInfo = objName.GetType().GetProperty(propertyName);
propertyInfo.SetValue(objName, value, null);

4
您可以使用 Type.InvokeMember 来实现这一点。
private void SetObjectProperty(string propertyName, string value, rel objName) 
{ 
    objName.GetType().InvokeMember(propertyName, 
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, 
        Type.DefaultBinder, objName, value); 
} 

2
您可以通过反射来实现:

void SetObjectProperty(object theObject, string propertyName, object value)
{
  Type type=theObject.GetType();
  var property=type.GetProperty(propertyName);
  var setter=property.SetMethod();
  setter.Invoke(theObject, new ojbject[]{value});
}

注意:为了易读性,故意省略了错误处理。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接