c#4.0中的dynamic早已不是新聞了,雖然內部用反射機制,略微會有一些效能上的額外開銷,但是有些特殊情境還是很有用的,二害相權,取其輕吧(也正是因為這些動態編程特性,Python,Ruby這類動態語言能更方便的融入到.net平台中)
using System;using System.Collections.Generic;using System.Dynamic;namespace DynamicTest{ class Program { public static void Main(string[] args) { dynamic obj = new ExpandoObject(); //動態添加一些屬性 obj.name = "Jimmy"; obj.age = 30; //動態添加一個方法 obj.sayHello = new Action<string>(SayHello); foreach (var item in (IDictionary<string, object>)obj) { if (item.Key == "sayHello") { //調用動態添加的方法 Action<string> a = item.Value as Action<String>; a("CLR 4.0"); } else { Console.WriteLine("key={0},value={1}", item.Key, item.Value); } } Console.WriteLine("-----------------------------------------------"); var d = (IDictionary<string, object>)obj; d.Remove("name");//刪除name屬性 d.Remove("sayHello");//刪除動態添加的方法 d.Remove("notExist");//刪除一個並不存在的東西(不會引發異常) foreach (var item in (IDictionary<string, object>)obj) { Console.WriteLine("key={0},value={1}", item.Key, item.Value); } Console.Read(); } public static void SayHello(string msg) { Console.WriteLine("Hello,{0}!", msg); } }}
運行結果:
key=name,value=Jimmy
key=age,value=30
Hello,CLR 4.0!
------------------------------
key=age,value=30