使用反射设置对象属性在C#中是否有一种方法可以使用反射来设置对象属性?例:MyObject obj = new MyObject();obj.Name = "Value";我想obj.Name带着倒影。类似于:Reflection.SetProperty(obj, "Name") = "Value";有办法吗?
3 回答

FFIVE
TA贡献1797条经验 获得超6个赞
Type.InvokeMember()
:
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);}

SMILET
TA贡献1796条经验 获得超4个赞
Type type = target.GetType();PropertyInfo prop = type.GetProperty("propertyName");prop.SetValue (target, propertyValue, null);
- 3 回答
- 0 关注
- 735 浏览
添加回答
举报
0/150
提交
取消