■ Dynamic type and anonymous type
An anonymous type is a type that is neither named nor individually defined. Strictly speaking, this type still has a name, only in the C # Source code We cannot see this name. However, before version 4.0, the range of anonymous types that can be effectively used is not very large. It is not impossible to use the anonymous type outside a method, but reflection must be used to use the anonymous type outside the method.
However, the dynamic type easily solves this problem. If it is returned as a dynamic type, it is easy to access its content.
Access objects of dynamic and anonymous types
Using system; Class Program { Private static dynamic GetObject () { Return new {yourname = "Asian", yourscore = 1000 }; } Static void main (string [] ARGs) { Dynamic A = GetObject (); Console. writeline ("{0} scored {1. ", A. yourname, A. yourscore ); } } |
Execution result of the above example
The Asian team scored 1000 points. |
Of course, because the type is not defined separately in C #, even if the name of the member to be accessed is wrong, it will not cause compilation errors, but throw an exception at runtime.
■ Dynamic Summary
Summarize the summary of dynamic.
●
The dynamic type is interpreted during running.
●
Attackers can access the information of objects of the type during compilation.
●
As long as the names are consistent, you can access any type, even if you do not know the type object information.
●
Makes it easier to use the anonymous type.
●
If a spelling error occurs, the name of the member to be accessed does not produce a compilation error, but throws an exception during runtime.
●
Although you do not know the type, you can access the object, but it will be at the cost of a small amount of performance.
The dynamic type cannot be an absolute possibility. Before that, reflection can also implement the same function. The dynamic type only makes it easier.
If you are very concerned about its impact on performance, there is also a corresponding countermeasure, that is, adopting parallel. At the same time, flexible use of system resources can effectively reduce performance disadvantages to a minimum. We will introduce this in the next chapter.