157 recommendations for writing high-quality code to improve C # programs--Recommendation 15: Use dynamic to simplify reflection implementation

Source: Internet
Author: User

Recommendation 15: Use dynamic to simplify reflection implementation

Dynamic is a new feature of the Framework 4.0. The advent of dynamic gives C # The characteristics of a weak language type. The compiler no longer checks the type at compile time, and the compiler default dynamic object supports whatever features the developer wants. For example, even if you know nothing about the objects returned by the Getdynamicobject method, you can call the code as follows, and the compiler will not error:

    Dynamic DynamicObject = getdynamicobject ();      Console.WriteLine (dynamicobject.name);      

Of course, if the runtime dynamicobject does not contain the specified attributes (such as the method SampleMethod with the return value above), the runtime program throws a Runtimebinderexception exception:

"System.Dynamic.ExpandoObject" does not contain the definition of "SampleMethod".

Note that someone will compare the Var keyword to the dynamic. In fact, var and dynamic are completely two concepts that should not be compared at all. var is actually the "syntactic sugar" that is thrown at compile time, and once compiled, the compile time automatically matches the actual type of the VAR variable and replaces the declaration of that variable with the actual type, which looks as if we were declaring it in the actual type when we coded it. When dynamic is compiled, it is actually an object type, except that the compiler makes special processing of the dynamic type so that it does not perform any type checking during compilation, but instead puts type checking into the runtime.

This can be seen from the editor window of Visual Studio. Variables declared with VAR support IntelliSense because Visual Studio can infer the actual type of the var type, whereas variables declared with dynamic do not support IntelliSense because the compiler knows nothing about the type of its run time. Using IntelliSense for dynamic variables prompts that this operation will resolve at run time.

With this feature of dynamic, you can simplify the reflection syntax in C #. Before the dynamic appears, assume that there is a class, the code looks like this:

     Public class Dynamicsample      {          publicstringgetset;}                 Public int ADD (intint  b)          {              return a + b;          }      

We use reflection in this way, and the caller code looks like this:

    New dynamicsample ();       var typeof (Dynamicsample). GetMethod ("Add");       int re = (intnewobject12

After using dynamic, the code looks more concise and reduces the chance of unpacking in a manageable range, as shown in the following code:

    New dynamicsample ();       int Re2 = Dynamicsample2.add (12

We might dismiss this simplification, after all, the code doesn't look much less, but if you take into account the two features of efficiency and elegance, then the advantages of dynamic are apparent. If the above code is executed 1 million times, as follows:

    intTimes =1000000; Dynamicsample Reflectsample=Newdynamicsample (); varAddmethod =typeof(Dynamicsample). GetMethod ("ADD"); Stopwatch Watch1=stopwatch.startnew ();  for(vari =0; I < times; i++) {Addmethod.invoke (reflectsample,New Object[] {1,2 }); } Console.WriteLine (string. Format ("reflection time: {0} milliseconds", Watch1.      Elapsedmilliseconds)); Dynamic Dynamicsample=Newdynamicsample (); Stopwatch WATCH2=stopwatch.startnew ();  for(inti =0; I < times; i++) {Dynamicsample.add (1,2); } Console.WriteLine (string. Format ("Dynamic time: {0} milliseconds", Watch2. Elapsedmilliseconds)); 

The output is:

Reflection Time: 2575 ms

Dynamic Time: 76 ms

As can be seen, there is no optimized reflection implementation, the above loop execution efficiency is much lower than the performance of the dynamic implementation. If the reflection implementation is optimized, the code looks like this:

Dynamicsample Reflectsamplebetter =Newdynamicsample (); varADDMETHOD2 =typeof(Dynamicsample). GetMethod ("ADD"); varDelg = (Func<dynamicsample,int,int,int>) delegate.createdelegate (typeof(Func<dynamicsample,int,int,int>), ADDMETHOD2); Stopwatch Watch3=stopwatch.startnew ();  for(vari =0; I < times; i++) {Delg (Reflectsamplebetter,1,2); } Console.WriteLine (string. Format ("Optimized reflection time: {0} milliseconds", Watch3. Elapsedmilliseconds)); 

The output is:

Optimized reflection time: 12 ms

It can be seen that the optimized reflection is implemented with its efficiency and dynamic at an order of magnitude. But it brings efficiency, but at the expense of the cleanliness of the code, this implementation in my opinion is not worth the candle. So, now that we have the dynamic type, we recommend that you:

Always use dynamic to simplify reflection implementations.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 15: Use dynamic to simplify reflection implementation

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.