C #4.0 provides a dynamic keyword. So what is dynamic and how does dynamic work?
Start with the simplest example:
Copy codeThe Code is as follows: static void Main (string [] args)
{
Dynamic dyn = 1;
Object obj = 1;
// Place the mouse in "dyn" and "obj" during compilation and you will find that:
// Dyn: local variable dynamic (dyn)
// Obj: local variable object (obj)
System. Console. WriteLine (dyn. GetType ());
System. Console. WriteLine (obj. GetType ());
}
Running this code will display the runtime types of dyn and obj:
System. Int32
System. Int32
Add two lines after the WriteLine method:
Dyn = dyn + 3;
Obj = obj + 3;
Compile:
We can see that for the expression obj + 3, the compiler reports an error, but does not report dyn + 3 compilation.
The compiler does not check the expression containing dyn because dyn is a dynamic.
Type conversion
Modify the Main Code as follows:
Dynamic dyn = (dynamic) 1;
Int j = (int) dyn;
We can see that 1 is forcibly converted to dynamic, and then forcibly converted back to int.
However, dynamic can be implicitly converted to any type, and can also be converted back from other types,
So the above Code is equivalent to the following:
Dynamic dyn = 1;
Int j = dyn;
Add the following code to modify the Main code:
// The following statement cannot be compiled, and the typeof operator cannot be used for dynamic types.
// Console. WriteLine (typeof (dynamic ));
Console. WriteLine (typeof (List <dynamic> ));
If you are a typeof (dynamic), the typeof operator cannot be used in a dynamic type,
However, if you write List <dynamic>, the output result is as follows:
The System. Object in the output is displayed.
Microsoft explained the following:
In most cases,The dynamic type and object type have the same behavior.. However, the compiler will not be used to parse or check operations that contain dynamic expression types. The compiler packs the information about the operation together and then uses the information for computing runtime operations. In this process, the variables of the Type dynamic are compiled into the variables of the type object. Therefore, the Type dynamic only exists during compilation and does not exist during runtime.