C #4.0 full parsing of dynamic keywords)

Source: Internet
Author: User

There are two problems:

◆ Intelligent awareness is missing when writing a program;

◆ Program running is slow (reflection ).

After reading new features in CSHARP today
4.docx just understands that it's okay to sort out things and hope to provide some reference for friends who do not know what dynamic is for now. Of course, I am not sure that all my views are correct. I hope you can use a dialectical perspective to read this article. If there are any mistakes, please criticize and correct them.

To put it bluntly, the dynamic keyword is used to declare a dynamic object and then call a method or read/write attribute through the dynamic object.

When using C #
2.0 or 3.0, if an object needs to be determined at runtime, and there is no interface or base class information, we generally use the reflection technology to call the method or attribute of this unknown object, while C #
The dynamic provided in 4.0 can help us simplify this work. Suppose our program will get an uncertain type object at runtime, but this object will certainly have a print () method. We need to call this method to print some information, then in C #
4.0 below, we can use the following two sentences of code to achieve this requirement.

This solution is much simpler than calling the print method through reflection? What programmers need to do is not to mistake the method name print (). vs2010 does not provide smart prompts for dynamic objects, because vs does not know what the unknowobj will be at runtime ......

At this point, many friends can see from this example that when the program is compiled to unknowobj. when print () is used, Vs will generate the reflected code and call the print method in the reflection mode. In essence, it will automatically reflect the code.

If you can understand this, it is not difficult to understand why C # is engaged in dynamic, a monster that is neither intelligent perception nor slow to run.

According to new features in CSHARP 4, dymanic is mainly used in the following scenarios:

1. Automatic reflection

2. COM component interoperability

3. mixed programming, such as ironruby and ironpython

4. Process html dom objects

If you have any friends who have handled the above jobs, it is not difficult to understand.

For more information, see new features in CSHARP 4. The above describes the dynamic of C #4.0.

C #4.0 dynamic usage (1) -- use reflection
This article from the beat search school: http://www.pasou.cn/edu/html/List18250.html

When designing the framework architecture, one of the headaches is that reflection is everywhere, but with C #4.0, dynamic can completely replace reflection, which makes me a little excited, immediately upgrade the first reflected code in the log tracker framework to C #4.0 in vs2010. The results are not disappointing at all, and the code is much simpler.
 
Let's take a look at the code after replacing the reflection with dynamic:
 
1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5 using system. reflection;
6 using system. IO;
7 /********************************
8 * updated by Lihua at 03/13/2009
9 *
10 * update functions:
11*1. Upgrade to C #4.0 and add dynamic to replace reflection
12*2. If zivsoft. log. dll does not exist, logs are not output.
13*3. Project compilation does not depend on zivsoft. log. dll
14 *************************************** */
15 namespace zivsoft. Data
16 {
17 /// <summary>
18 // only use classes in the persistent data layer framework
19 /// </Summary>
20 internal class Logger
21 {
22 Private Static Assembly _ assemblyfile;
23 private static dynamic _ logger;
24 static logger ()
25 {
26 var strdllfile = appdomain. currentdomain. basedirectory + "zivsoft. log. dll ";
27 if (file. exists (strdllfile ))
28 {
29 _ assemblyfile = assembly. LoadFile (strdllfile );
30 try
31 {
32 _ logger = _ assemblyfile. createinstance ("zivsoft. log. Logger", false, bindingflags. createinstance, null );
33}
34 catch {
35 _ logger = NULL;
36}
37}
38}
39
40 public static void loginfo (string message, Params object [] ARGs)
41 {
42 if (null! = _ Logger)
43 {
44 _ logger. loginfo (message, argS );
45}
46}
47
48 public static void logwarning (string message, Params object [] ARGs)
49 {
50 if (null! = _ Logger)
51 {
52 _ logger. logwarning (message, argS );
53}
54}
55
56 public static void logerror (string message, Params object [] ARGs)
57 {
58 If (null! = _ Logger)
59 {
60_logger. logerror (message, argS );
61}
62}
63
64 public static void logdebug (string message, Params object [] ARGs)
65 {
66 If (null! = _ Logger)
67 {
68 _ logger. logdebug (message, argS );
69}
70}
71
72 public static void logerror (exception E)
73 {
74 logerror ("{0}", e );
75}
76}
77}
78
 
The above is the entrance code for the persistent data layer to call the log tracker. I used reflection. I just changed it with dynamic. After debugging, there was no problem at all, so I was delighted, because many of my frameworks adopt reflection mechanisms that may be replaced by dynamic, such as the reflected sqlserver, MySQL, access and other databases in the persistent data layer framework.
 
I don't want to write much. Let's take a closer look.

Simplify com interoperability for dynamic applicationsC #4.0 includes multiple features, improving the interoperability with traditional com APIs, such as office automation. Dynamic types, named parameters, and optional parameters are also part of the improvement. Many com methods allow the parameter and return value types to be objects. Therefore, for a strongly typed language such as C #, a large amount of forced type conversion is required. However, in C #4.0, if the/link option is added during compilation, the dynamic type will produce new results: it makes the object type (parameter type or return type) in the COM interface method signature considered as dynamic, thus avoiding a lot of type conversion work. For example, the following statement is compared. // Dynamic is not used. (Excel. range) excel. cells [1, 1]). value2 = "name"; excel. range = (Excel. range) excel. cells [1, 1]; // dynamic and Excel are used. cells [1, 1]. value = "name"; excel. range = excel. cells [1, 1]; Hybrid programming of dynamic applications (The following is an example of calling ironpython using dynamic)

Using ironpython. hosting; using Microsoft. scripting. hosting; console. writeline ("loading random. PY... "); scriptruntime py = python. createruntime (); Dynamic Random = py. usefile ("random. PY "); console. writeline ("random. PY loaded! "); Var items = enumerable. range (1, 7 ). toarray (); For (int s = 0; S <10000; s ++) {random. shuffle (items); console. write ("sequence {0}:", S); foreach (int I in items) {console. write ("{0}", I);} console. writeline ();} for an object or expression of the dynamic type, the role of the compiler is to encapsulate the action expected to be executed by each expression and check the stored information at runtime, any invalid statement triggers a running exception. The result type of most dynamic operations is also dynamic. For example, if you move the cursor over testsum in the following example, the smart prompt displays (local variable) Dynamic testsum. Dynamic d = 1; var testsum = d + 3; // move the cursor over testsum below. system. Console. writeline (testsum );

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.