dynamic in C #4.0 is no longer news. Although the reflection mechanism is used internally, it has some extra performance overhead, but it is useful in some special scenarios, let's take it lightly (because of these dynamic programming features, dynamic languages such as Python and Ruby can be more easily integrated.. NET platform)
Using system; using system. collections. generic; using system. dynamic; namespace dynamictest {class program {public static void main (string [] ARGs) {dynamic OBJ = new expandoobject (); // dynamically add some attributes obj. name = "Jimmy"; obj. age = 30; // dynamically Add a method obj. sayhello = new action <string> (sayhello); foreach (VAR item in (idictionary <string, Object>) OBJ) {If (item. key = "sayhello") {// call the dynamically added 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"); // delete the name attribute D. remove ("sayhello"); // Delete the dynamically added method D. remove ("notexist"); // delete an existing item (no exception will be thrown) 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 );}}}
Running result:
Key = Name, value = Jimmy
Key = age, value = 30
Hello, CLR 4.0!
------------------------------
Key = age, value = 30