可能重复:
.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
}
Run Code Online (Sandbox Code Playgroud)
最后,电话:
SetObjectProperty("nameOfProperty", textBoxValue.Text, ref objName);
Run Code Online (Sandbox Code Playgroud)
希望这个问题足够充实.如果您需要更多详细信息,请告诉我们.
谢谢你的答案!
jos*_*uan 59
objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)
Jam*_*mes 37
您可以使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62565 次 |
| 最近记录: |