The c Dynamic compilation execution object method example USES the mapping mechanism to create objects
- 2020-06-03 08:05:46
- OfStack
C# is a compiled language, program execution, first through the compiler compilation, how to make C# like a script 1, when to execute, compile, here, we can use CSharpCodeProvider Microsoft.CSharp space to provide classes, to achieve the effect of dynamic compilation. Here, I create a new console program that references using System.CodeDom.Compiler in the Program.cs class.
using System. Reflection; using Microsoft. CSharp; Three large namespaces
#region using directiry
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
#endregion
/*==============================================================================
*
* author:lichaoqiang@163.com
* link:http://my.oschina.net/lichaoqiang
*
*
* ============================================================================*/
namespace CodeDom
{
class Program
{
#region Main program entry
/// <summary>
/// Main program entry
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//1> instantiation C# Code services provide objects
CSharpCodeProvider provider = new CSharpCodeProvider();
//2> Declare compiler parameters
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
try
{
//3> Dynamic compilation
CompilerResults result = provider.CompileAssemblyFromSource(parameters, BuildCSharpCode());
if (result.Errors.Count > 0)
{
Console.Write(" Compile error! ");
}
//4> If no compilation error occurs, the dynamic assembly has been generated at this point LCQ.LCQClass
//5> Started to play C# mapping
Assembly assembly = result.CompiledAssembly;
object obj = assembly.CreateInstance("LCQ.LCQClass");
Type type = assembly.GetType("LCQ.LCQClass");
//6> Get object method
MethodInfo method = type.GetMethod("Sum");
object[] objParameters = new object[2] { 1, 5 };
int iResult = Convert.ToInt32(method.Invoke(obj, objParameters));// Wake up the object and perform the action
Console.Write(iResult);
Console.Read();
}
catch (System.NotImplementedException ex)
{
Console.Write(ex.Message);
}
catch (System.ArgumentException ex)
{
Console.Write(ex.Message);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
#endregion
#region Generate code blocks
/// <summary>
/// Generate code blocks
/// </summary>
/// <returns></returns>
private static string BuildCSharpCode()
{
string fileName = AppDomain.CurrentDomain.BaseDirectory.Replace("Debug", string.Empty).Replace("Release", string.Empty) + "CodeFile.cs";
string strCodeDom = File.ReadAllText(fileName);
return strCodeDom;
}
#endregion
}
}