English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Dynamischer Typ (Dynamic)

C#4.0 (.NET 4.5) introduced a new type named dynamic, which avoids compile-time type checking. Dynamic types skip type checking at compile time; instead, they resolve types at runtime.

Dynamic type variables are defined using the keyword dynamic.

dynamic MyDynamicVar = 1;

In most cases, the compiler will compile dynamic types to object types. However, the actual type of dynamic type variables will be resolved at runtime.

dynamic MyDynamicVar = 1;
Console.WriteLine(MyDynamicVar.GetType());
Output:

System.Int32

Dynamic types change at runtime based on the assigned value. The following example shows how a dynamic variable changes its type based on the assigned value.

static void Main(string[] args)
{
    dynamic MyDynamicVar = 100;
    Console.WriteLine("Value: {0}, Type: {1)", MyDynamicVar, MyDynamicVar.GetType());
    MyDynamicVar = "Hello World!!";
    Console.WriteLine("Value: {0}, Type: {1)", MyDynamicVar, MyDynamicVar.GetType());
    MyDynamicVar = true;
    Console.WriteLine("Value: {0}, Type: {1)", MyDynamicVar, MyDynamicVar.GetType());
    MyDynamicVar = DateTime.Now;
    Console.WriteLine("Value: {0}, Type: {1)", MyDynamicVar, MyDynamicVar.GetType());
}
Output:
Value:100, Type: System.Int32
Value: Hello World !!, Type: System.String
Value: True, Type: System.Boolean
Value: 01-01-2014, Type: System.DateTime

Dynamic type variables are implicitly converted to other types.

dynamic d1 = 100;
int i = d1;
d1 = "Hello";
string greet = d1;
d1 = DateTime.Now;
DateTime dt = d1;

Methods and parameters

If an object of a class is assigned to a dynamic type, the compiler will not check the correct method and property names of the dynamic type that saves a custom class object. See the following example.

class Program
{
    static void Main(string[] args)
    {
        dynamic stud = new Student();
        stud.DisplayStudentInfo(1, "Bill");// Runtime error, no compile-time error
        stud.DisplayStudentInfo("1");// Runtime error, no compile-time error
        stud.FakeMethod();// Runtime error, no compile-time error
    }
}
public class Student
{
    public void DisplayStudentInfo(int id)
    {
    }
}

Im obigen Beispiel überprüft der C#-Compiler die Parameter, den Typ oder existiert er nicht, nicht. Er überprüft diese Inhalte bei der Laufzeit und wirft eine Laufzeitexception, wenn sie ungültig sind. Beachten Sie, dass dynamische Typen Visual Studio IntelliSense nicht unterstützen. Beachten Sie, dass dynamische Typen Visual Studio IntelliSense nicht unterstützen.

Das API für die dynamische Sprachumgebung (DLR) bietet die Grundstruktur zur Unterstützung dynamischer Typen in C#.