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)