C# 4 dynamic 動態對象 動態類型轉換

來源:互聯網
上載者:User

標籤:des   style   color   io   os   ar   使用   strong   sp   

public class User        {//使用省缺參數,一般不需要再為多態做各種靜態重載了public User( string name = "anonym", string type = "user" )                {this.UserName = name;this.UserType = type;                 }public UserName { private set; get; }public UserType { private set; get; }        }User user = new User();  //不帶任何參數執行個體化Console.WriteLine( user.UserName );  //輸出 anonymConsole.WriteLine( user.UserType );    //輸出 user// dynamic 關鍵字可以繞過靜態語言的強型別檢查dynamic d = user;Console.WriteLine( d.UserName );      //輸出 anonymConsole.WriteLine( d.UserType );        //輸出 user// ExpandoObject 是一個特殊對象,包含運行時可動態添加或移除的成員dynamic eo = new System.Dynamic.ExpandoObject();        eo.Description = "this is a dynamic property";Console.WriteLine( eo.Description );    // 輸出 this is a dynamic property//繼承 DynamicObject 類,重寫 TryInvokeMember 虛擬方法public class Animal : DynamicObject        {//嘗試執行成員,成功返回 true,並從第二個參數輸出執行後的傳回值public override bool TryInvokeMember( InvokeMemberBinder binder, object[] args, out object result)               {bool success = base.TryInvokeMember( binder, args, out result);//基類嘗試執行方法,返回 false,表示方法不存在,out 輸出 null 值//if (! success)  result = null;//若返回 false 將拋出異常return true;               }        }//派生動態類public class Duck : Animal        {public string Quack()              {return "Quack!!";              }        }//派生動態類public class Human : Animal        {public string Talk()              {return "Talk!!";              }         }//調用動態方法public static string DoQuack( dynamic animal )        {string result = animal.Quack();return result ?? "Null";  //(result == null)? "Human" : result;         }var duck = new Duck();var human = new Human();Console.WriteLine( DoQuack( duck ) );      //輸出 QuackConsole.WriteLine( DoQuack( human ) );   //輸出 Null , Human類不包含Quack方法,執行失敗

C# 4 dynamic 動態對象 動態類型轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.