C # dynamic Code Execution

Source: Internet
Author: User
Dynamic Code Execution, similar to the script engine. Yes Program During the execution period, a section of C # code is read from a string or text file, dynamically compiled into an assembly in the memory, and related types of instances are created to execute relevant methods.

For specific implementation, refer to the following code. To generate an assembly file, see use codedom to generate an assembly. Using system;
Using system. reflection;
Using system. Globalization;
Using Microsoft. CSHARP;
Using system. codedom;
Using system. codedom. compiler;

namespace consoleapplication1
{< br> public class Program
{< br> static void main (string [] ARGs)
{< br> // defines the C # code string to be dynamically executed. Of course, it can also be read from text files.
string code = @ "
using system;
namespace mynamespace
{< br> public class myclass
{< br> private string name;

Public myclass (string name)
{
This. Name = Name;
}

Public void test ()
{
Console. writeline ("{0}-{1}" ", name, datetime. Now );
}
}
}
";

// Create a compiler object
Csharpcodeprovider P = new csharpcodeprovider ();
Icodecompiler cc = P. createcompiler ();

// Set compilation Parameters
Compilerparameters Options = new compilerparameters ();
Options. referencedassemblies. Add ("system. dll ");
Options. generateinmemory = true;
Options. outputassembly = "mytest ";

// Start Compilation
Codesnippetcompileunit Cu = new codesnippetcompileunit (CODE );
Compilerresults Cr = cc. compileassemblyfromdom (options, Cu );

// Execute content related to the dynamic assembly.
Type T = Cr. compiledassembly. GetType ("mynamespace. myclass ");
Object o = Cr. compiledassembly. createinstance ("mynamespace. myclass", false, bindingflags. Default,
Null, new object [] {"Tom"}, cultureinfo. currentculture, null );
T. invokemember ("test", bindingflags. instance | bindingflags. Public | bindingflags. invokemethod,
Null, O, null );

}
}
}0 0

0

(Please Article Make comments)

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.