Web 發展推動動態語言蓬勃,CSDN 2007 調查關注度 12%,TIOBE 前十名佔六席。C# 持續吸收動態特性,4.0 以「動態編程」為主題。
C# 仍為靜態語言,但引入 dynamic 靜態類型,物件意義變得「動態」:結構與行為無法在編譯期完全捕獲,調用解析延遲至執行期。
public class Coffee { public string GetName() => "You selected Maxwell coffee."; }
public class Juice { public string GetName() => "You selected orange juice."; }
static object GetDrink(int i)
{
if (i == 1) return new Juice();
return new Coffee();
}
static void Main()
{
Console.WriteLine("Please Select Your Drink: 1 -- Juice; 2 -- Coffee");
int n = Console.Read();
dynamic drink = GetDrink(n);
Console.WriteLine(drink.GetName()); // 執行期決定呼叫哪個 GetName
}
GetDrink 回傳 object,賦值給 dynamic 變數後,drink.GetName() 編譯通過,執行時依實際型別 (Juice 或 Coffee) 分派。