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 ); //輸出 anonym Console.WriteLine( user.UserType ); //輸出 user // dynamic 關鍵字可以繞過靜態語言的強類型檢查 dynamic d = user; Console.WriteLine( d.UserName ); //輸出 anonym Console.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 ) ); //輸出 Quack Console.WriteLine( DoQuack( human ) ); //輸出 Null , Human類不包含Quack方法,執行失敗