日期:2014-05-18 浏览次数:20551 次
static void Main(string[] args) { dynamic d = new MyDynamicObject(); d.ojlovecd = "ojlovecd"; Console.WriteLine(d.ojlovecd); } class MyDynamicObject : System.Dynamic.DynamicObject { private Dictionary<string, object> dic = new Dictionary<string, object>(); public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result) { return dic.TryGetValue(binder.Name, out result) || base.TryGetMember(binder, out result); } public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value) { if (dic.ContainsKey(binder.Name)) dic[binder.Name] = value; else dic.Add(binder.Name, value); base.TrySetMember(binder, value); return true; } }
------解决方案--------------------
static void Main(string[] args) { dynamic d = new MyDynamicObject(); d.ManuallySetMember("Name", "ojlovecd"); Console.WriteLine(d.Name); } class MyDynamicObject : System.Dynamic.DynamicObject { private Dictionary<string, object> dic = new Dictionary<string, object>(); public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result) { return dic.TryGetValue(binder.Name, out result) || base.TryGetMember(binder, out result); } public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value) { if (dic.ContainsKey(binder.Name)) dic[binder.Name] = value; else dic.Add(binder.Name, value); base.TrySetMember(binder, value); return true; } public void ManuallySetMember(string key, object value) { if (dic.ContainsKey(key)) dic[key] = value; else dic.Add(key, value); } }
------解决方案--------------------
直接用 ExpendoObject 也可以。
dynamic person = new ExpandoObject(); var dict = (IDictionary<String, Object>)person; dict.Add("abcd", "test"); Console.WriteLine(person.abcd);
------解决方案--------------------