dynamic (C# 參考)dynamic (C# Reference)

dynamic 類型可讓發生它的作業略過編譯時期類型檢查。The dynamic type enables the operations in which it occurs to bypass compile-time type checking. 相反地,這些作業會在執行階段解決。Instead, these operations are resolved at run time. dynamic 類型會簡化 Office Automation API 這類 COM API 的存取、IronPython 程式庫這類動態 API 的存取,以及 HTML 文件物件模型 (DOM) 的存取。The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).

在大多數情況下,dynamic 類型的行為與 object 類型類似。Type dynamic behaves like type object in most circumstances. 不過,不會解決包含 dynamic 類型之運算式的作業,或編譯器不會對其進行類型檢查。However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. 編譯器會將作業資訊封裝在一起,而且稍後在執行階段會使用這項資訊來評估作業。The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. 在此程序期間,會將 dynamic 類型的變數編譯為 object 類型的變數。As part of the process, variables of type dynamic are compiled into variables of type object. 因此,dynamic 類型只存在於編譯時期,而非執行階段。Therefore, type dynamic exists only at compile time, not at run time.

下列範例會對照 dynamic 類型的變數與 object 類型的變數。The following example contrasts a variable of type dynamic to a variable of type object. 若要在編譯時期驗證每個變數的類型,請將滑鼠指標放在 WriteLine 陳述式中的 dynobj 上方。To verify the type of each variable at compile time, place the mouse pointer over dyn or obj in the WriteLine statements. IntelliSense 會顯示「動態」來表示 dyn,並顯示「物件」來表示 objIntelliSense shows dynamic for dyn and object for obj.

class Program
{
    static void Main(string[] args)
    {
        dynamic dyn = 1;
        object obj = 1;

        // Rest the mouse pointer over dyn and obj to see their
        // types at compile time.
        System.Console.WriteLine(dyn.GetType());
        System.Console.WriteLine(obj.GetType());
    }
}

WriteLine 陳述式會顯示執行階段類型 dynobjThe WriteLine statements display the run-time types of dyn and obj. 此時,兩者都有相同的類型:整數。At that point, both have the same type, integer. 會產生下列輸出:The following output is produced:

System.Int32

System.Int32

若要查看 dynobj 在編譯時期的差異,請在上述範例的宣告與 WriteLine 陳述式之間新增下列兩行。To see the difference between dyn and obj at compile time, add the following two lines between the declarations and the WriteLine statements in the previous example.

dyn = dyn + 3;  
obj = obj + 3;  

嘗試新增運算式 obj + 3 中的整數和物件時報告編譯器錯誤。A compiler error is reported for the attempted addition of an integer and an object in expression obj + 3. 不過,不會回報 dyn + 3 的錯誤。However, no error is reported for dyn + 3. 在編譯時期不會檢查包含 dyn 的運算式,因為 dyn 的類型是 dynamicThe expression that contains dyn is not checked at compile time because the type of dyn is dynamic.

內容Context

在下列情況下,dynamic 關鍵字可能會直接出現,或作為建構類型的元件︰The dynamic keyword can appear directly or as a component of a constructed type in the following situations:

  • 在宣告中,作為屬性、欄位、索引子、參數、傳回值、區域變數或類型條件約束的類型。In declarations, as the type of a property, field, indexer, parameter, return value, local variable, or type constraint. 下列類別定義在數個不同宣告中使用 dynamicThe following class definition uses dynamic in several different declarations.

    class ExampleClass
    {
        // A dynamic field.
        static dynamic field;
    
        // A dynamic property.
        dynamic prop { get; set; }
    
        // A dynamic return type and a dynamic parameter type.
        public dynamic exampleMethod(dynamic d)
        {
            // A dynamic local variable.
            dynamic local = "Local variable";
            int two = 2;
    
            if (d is int)
            {
                return local;
            }
            else
            {
                return two;
            }
        }
    }
    
  • 在明確類型轉換中,作為轉換的目標類型。In explicit type conversions, as the target type of a conversion.

    static void convertToDynamic()
    {
        dynamic d;
        int i = 20;
        d = (dynamic)i;
        Console.WriteLine(d);
    
        string s = "Example string.";
        d = (dynamic)s;
        Console.WriteLine(d);
    
        DateTime dt = DateTime.Today;
        d = (dynamic)dt;
        Console.WriteLine(d);
    
    }
    // Results:
    // 20
    // Example string.
    // 2/17/2009 9:12:00 AM
    
  • 在任何內容中,其中類型作為值 (例如 is 運算子或 as 運算子右側) 或作為部分建構類型之 typeof 的引數。In any context where types serve as values, such as on the right side of an is operator or an as operator, or as the argument to typeof as part of a constructed type. 例如,dynamic 可以用於下列運算式中。For example, dynamic can be used in the following expressions.

    int i = 8;
    dynamic d;
    // With the is operator.
    // The dynamic type behaves like object. The following
    // expression returns true unless someVar has the value null.
    if (someVar is dynamic) { }
    
    // With the as operator.
    d = i as dynamic;
    
    // With typeof, as part of a constructed type.
    Console.WriteLine(typeof(List<dynamic>));
    
    // The following statement causes a compiler error.
    //Console.WriteLine(typeof(dynamic));
    

範例Example

下列範例會在數個宣告中使用 dynamicThe following example uses dynamic in several declarations. Main 方法也會對照編譯時期類型檢查與執行階段類型檢查。The Main method also contrasts compile-time type checking with run-time type checking.

using System;

namespace DynamicExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            ExampleClass ec = new ExampleClass();
            Console.WriteLine(ec.exampleMethod(10));
            Console.WriteLine(ec.exampleMethod("value"));

            // The following line causes a compiler error because exampleMethod
            // takes only one argument.
            //Console.WriteLine(ec.exampleMethod(10, 4));

            dynamic dynamic_ec = new ExampleClass();
            Console.WriteLine(dynamic_ec.exampleMethod(10));

            // Because dynamic_ec is dynamic, the following call to exampleMethod
            // with two arguments does not produce an error at compile time.
            // However, itdoes cause a run-time error. 
            //Console.WriteLine(dynamic_ec.exampleMethod(10, 4));
        }
    }

    class ExampleClass
    {
        static dynamic field;
        dynamic prop { get; set; }

        public dynamic exampleMethod(dynamic d)
        {
            dynamic local = "Local variable";
            int two = 2;

            if (d is int)
            {
                return local;
            }
            else
            {
                return two;
            }
        }
    }
}
// Results:
// Local variable
// 2
// Local variable

如需詳細資訊和範例,請參閱使用動態類型For more information and examples, see Using Type dynamic.

請參閱See Also

System.Dynamic.ExpandoObject
System.Dynamic.DynamicObject
使用動態型別Using Type dynamic
objectobject
isis
asas
typeoftypeof
如何:使用 as 和 is 運算子進行安全轉換How to: Safely Cast by Using as and is Operators
逐步解說:建立和使用動態物件Walkthrough: Creating and Using Dynamic Objects