標籤: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 動態對象 動態類型轉換