using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using System.Reflection;namespace WindowsFormsApplication30
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
string code = "int sum = 0; for(int i = 0; i < 100; i++) { sum += i; } MessageBox.Show(sum.ToString());";
Compiler(code);
} private void Compiler(string code)
{
CompilerParameters vCompilerParameters = new CompilerParameters();
vCompilerParameters.GenerateExecutable = false;
vCompilerParameters.GenerateInMemory = true;
vCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
string vSource =
"using System.Windows.Forms; " +
"public class Temp " +
"{ " +
" public void Test() " +
" { " +
" " + code + " " +
" } " +
"} ";
CompilerResults vCompilerResults =
CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(vCompilerParameters, vSource); Assembly vAssembly = vCompilerResults.CompiledAssembly;
object vTemp = vAssembly.CreateInstance("Temp");
MethodInfo vTest = vTemp.GetType().GetMethod("Test");
vTest.Invoke(vTemp, null);
} }
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using System.Reflection;namespace WindowsFormsApplication30
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
string code = "int sum = 0; for(int i = 0; i < 100; i++) { sum += i; } MessageBox.Show(sum.ToString());";
Compiler(code);
} private void Compiler(string code)
{
CompilerParameters vCompilerParameters = new CompilerParameters();
vCompilerParameters.GenerateExecutable = false;
vCompilerParameters.GenerateInMemory = true;
vCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
string vSource =
"using System.Windows.Forms; " +
"public class Temp " +
"{ " +
" public void Test() " +
" { " +
" " + code + " " +
" } " +
"} ";
CompilerResults vCompilerResults =
CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(vCompilerParameters, vSource); Assembly vAssembly = vCompilerResults.CompiledAssembly;
object vTemp = vAssembly.CreateInstance("Temp");
MethodInfo vTest = vTemp.GetType().GetMethod("Test");
vTest.Invoke(vTemp, null);
} }
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货