使用反射設(shè)置對(duì)象屬性在C#中是否有一種方法可以使用反射來(lái)設(shè)置對(duì)象屬性?例:MyObject obj = new MyObject();obj.Name = "Value";我想obj.Name帶著倒影。類(lèi)似于:Reflection.SetProperty(obj, "Name") = "Value";有辦法嗎?
3 回答

FFIVE
TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
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貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
Type type = target.GetType();PropertyInfo prop = type.GetProperty("propertyName");prop.SetValue (target, propertyValue, null);

神不在的星期二
TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
var wrapped = ObjectAccessor.Create(obj); wrapped[property] = "Bob";
- 3 回答
- 0 關(guān)注
- 763 瀏覽
添加回答
舉報(bào)
0/150
提交
取消