動態成員查詢

在 C#型別系統中引入了新的偽型別 dynamic。它被視為 System.Object,但此外,允許任何成員訪問(方法呼叫,欄位,屬性或索引器訪問,或委託呼叫)或運算子對此型別的值的應用而不進行任何型別檢查,並且決議推遲到執行時間。這被稱為鴨子打字或後期繫結。例如:

// Returns the value of Length property or field of any object
int GetLength(dynamic obj)
{
    return obj.Length;
}
  
GetLength("Hello, world");        // a string has a Length property,
GetLength(new int[] { 1, 2, 3 }); // and so does an array,
GetLength(42);                    // but not an integer - an exception will be thrown
                                  // in GetLength method at run-time

在這種情況下,動態型別用於避免更詳細的反射。它仍然在引擎蓋下使用 Reflection,但由於快取,它通常更快。

此功能主要針對與動態語言的互操作性。

// Initialize the engine and execute a file
var runtime = ScriptRuntime.CreateFromConfiguration();
dynamic globals = runtime.Globals;
runtime.ExecuteFile("Calc.rb");

// Use Calc type from Ruby
dynamic calc = globals.Calc.@new();
calc.valueA = 1337;
calc.valueB = 666;
dynamic answer = calc.Calculate();

動態型別甚至在大多數靜態型別程式碼中都有應用程式,例如,它使得雙重排程無需實現訪問者模式。