C#动态设置属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12970353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# dynamically set property
提问by David Archer
Possible Duplicate:
.Net - Reflection set object property
Setting a property by reflection with a string value
I have an object with multiple properties. Let's call the object objName. I'm trying to create a method that simply updates the object with the new property values.
我有一个具有多个属性的对象。让我们调用对象 objName。我正在尝试创建一个方法,该方法仅使用新的属性值更新对象。
I want to be able to do the following in a method:
我希望能够在方法中执行以下操作:
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
}
and finally, the call:
最后,电话:
SetObjectProperty("nameOfProperty", textBoxValue.Text, ref objName);
Hope the question is fleshed out enough. Let me know if you need more details.
希望这个问题足够充实。如果您需要更多详细信息,请告诉我。
Thanks for the answers all!
谢谢大家的回答!
采纳答案by josejuan
objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)
objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)
回答by James
You can use Reflectionto do this e.g.
您可以使用反射来做到这一点,例如
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);
}
}
回答by harriyott
Get the property info first, and then set the value on the property:
首先获取属性信息,然后在属性上设置值:
PropertyInfo propertyInfo = objName.GetType().GetProperty(propertyName);
propertyInfo.SetValue(objName, value, null);
回答by Ekk
You can use Type.InvokeMemberto do this.
您可以使用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);
}
回答by Sean
You can do it via reflection:
您可以通过反射来做到这一点:
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});
}
NOTE: Error handling intentionally left out for the sake of readability.
注意:为了可读性,故意省略了错误处理。

