Dynamic Programming in C #4.0

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.