C # dynamic keywords

Source: Internet
Author: User

 

C # Is a type-safe programming language (all expressions can be parsed into an instance of a certain type. In the code generated by the compiler, only operations of this type are executed ), compared with non-type security languages, the advantages of type security are as follows:

 

1. Many errors can be detected during compilation. The warranty code is correct before being executed.

 

2. During compilation, the language can usually generate smaller and faster code. (Perform more assumptions during compilation and implement those assumptions in IL and metadata)

 

 

 

To help developers use reflection or communicate with basic components, dynamic was born!

 

The code shows how to use reflection to call a method ("Contains") on a String target ("according to my search type "), pass a real parameter ("I am just a string parameter") to it and store the result to the result of the local variable.

 

Static void Main () {object target = ""; object arg = "I am only a string parameter"; Type [] argtype = new Type [] {arg. getType ()}; System. reflection. methodInfo method = target. getType (). getMethod ("Contains", argtype); object [] argm = new object [] {arg}; Boolean result = Convert. toBoolean (method. invoke (target, argm ));}

Now, with dynamic!

 

 

Static void Main () {dynamic target = ""; dynamic arg = "parameter"; Boolean result = target. Contains (arg );}

 

 

Is there any significant simplification.

 

Static void Main () {Application excel = new Application (); excel. visible = true; excel. workbooks. add (Type. missing); (Range) excel. cells [1, 1]). value = "characters in cells"; // if there is no dynamic type, excel. the returned Value of Cells [] is of the objec Type. You must convert the Value to the Rang type before accessing the Value attribute. Excel. cells [1, 1]. value = "characters in cells"; // generates a packaging assembly for the COM object that can be called by the "RunTime, any variant used in the COM method will actually be converted to dynamic, which is called dynamic (dynamicfication ). // Here, excel. Cells [] is of the dynamic type, and its Value can be accessed without the need to convert it to the Range type. Dynamic significantly simplifies the interoperability with COM objects. }

 

 

Let's get started with the magic of dynamic.

 

We can use dynamic expressions or variables to call a member, such as a field, attribute/indexer, method, delegate, and unary/binary/conversion operators, when our code calls a member using a dynamic expression or variable, the compiler generates a special IL code to describe the required operations.

 

This special code is called payload (payload) (these payload Code uses a class called runtime binder). At runtime, the payload Code determines the specific operation based on the actual type of the object referenced by the dynamic expression/variable.

 

Let's look at this example:

 

Static void Main () {for (int I = 0; I <2; I ++) {dynamic arg = (I = 0 )? (Dynamic) 10: "A"; dynamic result = plus (arg); // The first loop I = 0, arg = 10; so when the plus is called, the return value belongs to the int type. The second is string type. M (result); // The payload Code determines the actual type of the value passed to M, and then calls the corresponding overload method.} Console. readKey ();} static dynamic plus (dynamic arg) {return arg + arg;} static void M (int n) {Console. writeLine ("M (int): {0}", n);} static void M (string s) {Console. writeLine ("M (string): {0}", s );}}

 

 

If the field type, method parameter type, or method type is specified as dynamic, the compiler converts this type to System. object, and apply System to fields, parameters, or return types in metadata. runtime. compilerSevices. an instance of DynamicAttribute. If a local variable is specified as dynamic, the variable type will also become an Object, but DynamicAttribute will not be applied to the local variable. It should be used within the method.

 

Because dynamic is an object, it not only changes dynamic into an object, but also changes the object into dynamic to get two different method signatures. Example:

 

Object dd (dynamic I) {return I;} dynamic dd (object I) {return I ;}

This does not allow compilation.

 

Dynam type conversion:

 

Static void Main () {object o = 123; // (boxed) Int32 n = o; // error! Implicit conversions from objects to int32 are not allowed. Int32 n1 = (Int32) o; // converts an object to int32. (Unpack) dynamic od = 123; // (boxed) dynamic OS = "dsfsdf"; Int32 ns = OS; // an error is returned when running the command. Int32 nd = od; // implicitly converted from dynamic to int32 (unboxing) // in this example, when dynamic is converted to another type, the display transformation can be omitted. // However, CLR verifies the transformation at runtime to ensure the type security. If the object type is incompatible with the type to be converted to, clr throws an InvalidCastException.}

Differences between dynamic and var:

 

1. var declaring a local variable is just a simplified syntax that requires the compiler to deduce the specific data type based on an expression.

 

2. var can only be used to declare local variables in a method, while dynamic can be used to declare local variables, fields, and parameters.

 

3. The expression cannot be transformed into var, but dynamic.

 

4. variables declared with var must be explicitly initialized, but no variables declared with dynam need to be initialized.

 

Note the following when using dynamic:

 

At runtime, Microsoft. csharp. the dll must be loaded into the AppDomain, which damages the program performance and increases the consumption of inner errors. csharp. dll also loads System. dll and System. core. dll. If the dynamic and COM components are used for interoperability, the System will be loaded. dynamic. dll, payload code will generate dynamic code at runtime. These codes enter an Assembly that resides in the memory, called the "anonymous Hosted DynamicMethods Assembly" (Anonymously Hosted DynamicMethods Assembly ).

 

When a feature call uses a large number of calls from dynamic real parameters of the same runtime type, this code can enhance the scheduling performance.

 

Although dynamic can simplify syntax, the additional overhead of the dynamic evaluation function cannot be ignored. After all, loading all these sets and additional memory consumption will have an additional impact on performance. If the program only needs dynamic behavior in one or two places, the traditional approach may be more efficient.

 

From Tom

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.