. Dynamic compilation in net

Source: Internet
Author: User
Tags add object count execution extend net string tostring


The dynamic compilation and execution of code is one. NET platform provides us with a powerful tool to flexibly expand (and, of course, internal developers) complex and unpredictable logic, and to extend our existing applications with some additional code. This gives us, to a large extent, another way of extending (which, of course, is not strictly an extension, but at least gives us a clue).
Dynamic code execution can be applied to a number of occasions such as template generation, plus logical extensions. A simple example, for the Web site that response speed, HTML static page is often our best choice, but based on data-driven sites are often difficult to use static page implementation, then the dynamic page to generate HTML work may be a good application of the occasion. In addition, for some templates, we can also use it to do. In addition, this is in itself the way Plug-ins are written.
The most basic dynamic compilation
. NET provides us with a very strong support to achieve all this we can do on the basis of the main application of the two namespaces are: System.CodeDom.Compiler and Microsoft.csharp or Microsoft.VisualBasic. In addition, you need to use reflection to dynamically execute your code. The principle of dynamically compiling and executing code is to deliver the source code to CSharpCodeProvider to perform the compilation (in fact, the  is no different), if there are no compilation errors, The generated IL code is compiled into a DLL that is stored in memory and loaded in an application domain (which is implied to be current) and invoked by reflection in a way that invokes one of its methods or triggers an event, and so on. It's a way to write plug-ins, and because of that, we can organize and extend our programs with predefined excuses and return them to the main program to trigger. A basic procedure for dynamically compiling and executing code includes:
1. The code that will be compiled and executed is read in and saved as a string
2. Declaring a CSharpCodeProvider object instance
3. Call the CSharpCodeProvider instance's CompileAssemblyFromSource method compilation
4. Generate an instance of the generated object with Reflection (Assembly.createinstance)
5. Call its method
The following code fragment contains the complete compilation and execution process:


 

 
  1. Get the code to compile
  2. string strsourcecode = This.txtSource.Text;
  3. 1.Create a new Csharpcodeprivoder instance
  4. CSharpCodeProvider Objcsharpcodeprivoder = new CSharpCodeProvider ();
  5. 2.Sets the runtime compiling parameters by crating a new CompilerParameters instance
  6. CompilerParameters objcompilerparameters = new CompilerParameters ();
  7. OBJCOMPILERPARAMETERS.REFERENCEDASSEMBLIES.ADD ("System.dll");
  8. OBJCOMPILERPARAMETERS.REFERENCEDASSEMBLIES.ADD ("System.Windows.Forms.dll");
  9. Objcompilerparameters.generateinmemory = true;
  10. 3.compilerresults:complile the code snippet by calling a to the provider
  11. CompilerResults cr = Objcsharpcodeprivoder.compileassemblyfromsource (objcompilerparameters, StrSourceCode);
  12. if (CR. Errors.haserrors)
  13. {
  14. String strerrormsg = cr. Errors.Count.ToString () + "Errors:";
  15. for (int x = 0; x < cr. Errors.Count; X + +)
  16. {
  17. Strerrormsg = strerrormsg + "\r\nline:" +
  18. Cr. ERRORS[X]. Line.tostring () + "-" +
  19. Cr. ERRORS[X]. ErrorText;
  20. }
  21. This.txtResult.Text = strerrormsg;
  22. MessageBox.Show ("There were build Erros, please modify your code.", "compiling Error");
  23. Return
  24. }
  25. 4. Invoke the method by using Reflection
  26. Assembly objassembly = cr.compiledassembly;
  27. Object objclass = Objassembly.createinstance ("Dynamicly.helloworld");
  28. if (objclass = null)
  29. {
  30. This.txtResult.Text = "Error:" + "couldn ' t load class."
  31. Return
  32. }
  33. object[] objcodeparms = new Object[1];
  34. Objcodeparms[0] = "Allan."
  35. String strresult = (string) objclass.gettype (). InvokeMember ("GetTime", BindingFlags.InvokeMethod, NULL, objclass, objcodeparms);
  36. This.txtResult.Text = Strresult;




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.