想用dynamic代替反射,遇到如下问题
比如:
var a="abcd";
dynamic b=new object();
b.a="test" //我希望这个a是一个变量,值就是上面的"abcd"
可以吗?
------解决方案--------------------------------------------------------
- C# code
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; } }
------解决方案--------------------------------------------------------
- C# code
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 也可以。
- C# code
dynamic person = new ExpandoObject();var dict = (IDictionary<String, Object>)person;dict.Add("abcd", "test");Console.WriteLine(person.abcd);
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
看来看去,lz的场景只是一般的反射赋值。。。。
------解决方案--------------------------------------------------------
dynamic性能太低了,,,我以前做过一个很简单的小例子,一个dynamic方法和一个普通的方法,性能相差20倍。
------解决方案--------------------------------------------------------