Play to Dynamic compilation (i) Initial knowledge

Source: Internet
Author: User
Tags foreach reflection

The benefits of dynamic compilation are many, but I find that many people actually do not really understand or do not have the flexibility to use dynamic compilation, so powerful a function into a chicken. In my own use of the tool library there are many places in the use of dynamic compilation, later I will slowly release the code in the library, so the dynamic compilation of the relevant knowledge points sorted out

What is dynamic compilation?

My personal understanding is that during the program run, the string of C # code is compiled into an assembly object, and the compiled member is called by reflection on the assembly.

An explanation that's easier to understand is similar to the one in SQL Server

Exec

(' SELECT * from [table] ')

or in JavaScript.

var a = eval ("(function ()

{return 1;}")

Why use dynamic compilation?

1. In order to more easily solve some of the problems

For example, the value of the string that computes a formula "2+3* (4-1)/5%7"

To calculate the value of this formula, it is the simplest and most effective way to compile the output directly, just like this

Formula = 2 + 3 * (4-1)/5% 7 public
decimal GetValue (string formula)
{
    String code = @ ' public
        clas S Class1
        {public
            static decimal GetValue ()
            {return
                (decimal) ("+ Formula + @");
            }
        }
    ";
    Type type = dynamic compilation (code);
    return (decimal) type. GetMethod ("GetValue"). Invoke (null, NULL);

The above situation is the most basic one, it is also one of the easiest things to understand (as I personally do not recommend, because compiling an assembly itself consumes a lot of resources, the compiled object is normally not unloaded, and if dynamic compilation is extremely unwise to use only once)

2. For the better performance of the program

3, in order to program more flexible

4, for better scalability

5,.......

ps:2,3,4 these will be mentioned in the next article, here to sell first.

How to use dynamic compilation

First, construct a convenient and dynamic compilation method

Using Microsoft.csharp;
Using System;
Using System.CodeDom.Compiler;
Using System.Collections.Generic;
Using System.Reflection;
    
Using System.Text; Namespace Blqw {public class Dynamiccompile_1 {///<summary>//////</summary >///<param name= "code" > need to compile C # code </param>///<param name= ' usingtypes ' > Compile code to be referenced in the type & lt;/param>///<returns></returns> public static Assembly compileassembly (string code, para Ms Type[] Usingtypes {compilerparameters compilerparameters = new CompilerParameters ();//Parameters used in dynamic compilation  Like compilerparameters.generateexecutable = false;//do not need to generate executable compilerparameters.generateinmemory = true;//run directly in memory add the type that needs to be referenced hashset<string> ns = new hashset<string> ();//To
      To save the namespace, the 4.0 of this object, if the frame is 2.0, can use dictionary instead of foreach (var type in usingtypes) {          Ns. ADD ("using" + type.) Namespace + ";" + Environment.NewLine);//log namespace, because you do not want to repeat the use of HashSet compilerparameters.referencedassemblies . ADD (type. Module.fullyqualifiedname);//This is equivalent to introducing a DLL} code = string. Concat (NS) + code;//joins the using namespace code and declares the compiler using (CSharpCodeProvider Objcsharp Codeprivoder = new CSharpCodeProvider ()) {//start compiling compilerresults CR = Objcsha
    
                Rpcodeprivoder.compileassemblyfromsource (CompilerParameters, code); if (CR.
                    errors.haserrors)//If there are errors {StringBuilder SB = new StringBuilder (); Sb.
                    Appendline ("Compile Error:"); foreach (CompilerError err in CR. Errors) {sb. Appendline (Err.
                    ErrorText); } throw new Exception (sb.)
                ToString ());
    } else            {//returns the compiled assembly return cr.compiledassembly; }
            }
        }
    }
}

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.