c#4.0中的動態編程

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.