using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Reflection;
using System.Globalization;namespace test
{
public interface IMyClass
{
void Test();
}
class Program
{
static void Main(string[] args)
{
// 定义需要动态执行的 C# 代码字符串,当然也可从文本文件中读取。
string code = @"
using System;
namespace MyNamespace
{
public class MyClass:test.IMyClass
{
private string name; public MyClass(string name)
{
this.name = name;
} public void Test()
{
Console.WriteLine(""{0} - {1}"", name, DateTime.Now);
}
}
}
";
Console.WriteLine("{0}", DateTime.Now);
// 创建编译器对象
CSharpCodeProvider p = new CSharpCodeProvider(); // 设置编译参数
CompilerParameters options = new CompilerParameters();
options.ReferencedAssemblies.Add("System.dll");
options.GenerateInMemory = true;
//options.OutputAssembly = "MyTest"; // 开始编译
CodeSnippetCompileUnit cu = new CodeSnippetCompileUnit(code); CompilerResults cr = p.CompileAssemblyFromDom(options, cu); if (cr.Errors.HasErrors)
{
Console.WriteLine("编译错误:");
foreach (CompilerError err in cr.Errors)
{
Console.WriteLine(err.ErrorText);
}
}
else
{
// 通过反射,调用HelloWorld的实例
Assembly objAssembly = cr.CompiledAssembly;
object objHelloWorld = objAssembly.CreateInstance("MyNamespace.MyClass");
MethodInfo objMI = objHelloWorld.GetType().GetMethod("Test"); Console.WriteLine(objMI.Invoke(objHelloWorld, null));
} }
}
}test.ext控制台程序,编译没错,运行错误:
The type or namespace name 'test' could not be found (are you missing a using directive or an assembly reference?)
// 编译方法: csc /t:winexe SuperCalc.cs VBExpression.csusing System;
using System.Windows.Forms;
using Skyiv.Util;namespace Skyiv
{
class Calc : Form
{
TextBox tbxA1;
TextBox tbxA3; Calc()
{
Text = "Super Calculator";
StartPosition = FormStartPosition.CenterScreen;
Width = 300;
Height = 300; tbxA1 = new TextBox();
tbxA1.Parent = this;
tbxA1.Multiline = true;
tbxA1.WordWrap = false;
tbxA1.Dock = DockStyle.Fill;
tbxA1.BorderStyle = BorderStyle.FixedSingle; Panel pnlA1 = new Panel();
pnlA1.Parent = this;
pnlA1.Height = 22;
pnlA1.Dock = DockStyle.Top; tbxA3 = new TextBox();
tbxA3.Parent = pnlA1;
tbxA3.Dock = DockStyle.Fill;
tbxA3.BorderStyle = BorderStyle.FixedSingle;
tbxA3.ReadOnly = true; Button btnA3 = new Button();
btnA3.Text = "&Calculate";
btnA3.Parent = pnlA1;
btnA3.Width = 80;
btnA3.Dock = DockStyle.Left;
btnA3.Click += new EventHandler(Calc_Clicked);
} void Calc_Clicked(object sender, EventArgs ea)
{
(sender as Control).Enabled = false;
try
{
tbxA3.Text = (new Expression(tbxA1.Text)).Compute().ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
finally
{
(sender as Control).Enabled = true;
}
} [STAThread]
static void Main(string [] args)
{
Application.Run(new Calc());
}
}
}
// VBExpression.cs - 动态生成数学表达式并计算其值
// 表达式使用 Visual Baisc 语法
// 可使用 pi、e 等常量,sin、cos、tan、log、sqrt 等函数using System;
using System.CodeDom.Compiler;
using Microsoft.VisualBasic;
using System.Reflection;
using System.Text;
using System.Globalization;namespace Skyiv.Util
{
sealed class Expression
{
object instance;
MethodInfo method; public Expression(string expression)
{
if (expression.ToUpper(CultureInfo.InvariantCulture).IndexOf("RETURN") < 0)
{
expression = "Return " + expression.Replace(Environment.NewLine, " ");
}
string className = "Expression";
string methodName = "Compute";
CompilerParameters p = new CompilerParameters();
p.GenerateInMemory = true;
CompilerResults cr = new VBCodeProvider().CompileAssemblyFromSource
(
p,
string.Format
(
@"Option Explicit Off
Option Strict Off
Imports System, System.Math, Microsoft.VisualBasic
NotInheritable Class {0}
Public Function {1} As Double
{2}
End Function
End Class",
className, methodName, expression
)
);
if(cr.Errors.Count > 0)
{
string msg = "Expression(\"" + expression + "\"): \n";
foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
throw new Exception(msg);
}
instance = cr.CompiledAssembly.CreateInstance(className);
method = instance.GetType().GetMethod(methodName);
} public double Compute()
{
return (double)method.Invoke(instance, null);
}
}
}
using System.Collections.Generic;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Reflection;
using System.Globalization;namespace test
{
public interface IMyClass
{
void Test();
}
class Program
{
static void Main(string[] args)
{
// 定义需要动态执行的 C# 代码字符串,当然也可从文本文件中读取。
string code = @"
using System;
namespace MyNamespace
{
public class MyClass
{
private string name;
public MyClass():this(""World""){} public MyClass(string name)
{
this.name = name;
} public void Test()
{
Console.WriteLine(""{0} - {1}"", name, DateTime.Now);
}
}
}
";
Console.WriteLine("{0}", DateTime.Now);
// 创建编译器对象
CSharpCodeProvider p = new CSharpCodeProvider(); // 设置编译参数
CompilerParameters options = new CompilerParameters();
options.ReferencedAssemblies.Add("System.dll");
options.GenerateInMemory = true;
//options.OutputAssembly = "MyTest"; // 开始编译
CodeSnippetCompileUnit cu = new CodeSnippetCompileUnit(code); CompilerResults cr = p.CompileAssemblyFromDom(options, cu); if (cr.Errors.HasErrors)
{
Console.WriteLine("编译错误:");
foreach (CompilerError err in cr.Errors)
{
Console.WriteLine(err.ErrorText);
}
}
else
{
// 通过反射,调用HelloWorld的实例
Assembly objAssembly = cr.CompiledAssembly;
object objHelloWorld = objAssembly.CreateInstance("MyNamespace.MyClass");
MethodInfo objMI = objHelloWorld.GetType().GetMethod("Test"); Console.WriteLine(objMI.Invoke(objHelloWorld, null));
} }
}
}
然后装载编译,
然后装载编译,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace test
{
public interface IMyClass
{
void Test();
}
}
建立test3.exe
引用test4.dllusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Reflection;
using System.Globalization;namespace test
{
class Program
{
static void Main(string[] args)
{
// 定义需要动态执行的 C# 代码字符串,当然也可从文本文件中读取。
string code = @"
using System;
using test;
namespace MyNamespace
{
public class MyClass:test.IMyClass
{
private string name;public MyClass():this(""AA"")
{} public MyClass(string name)
{
this.name = name;
} public void Test()
{
Console.WriteLine(""{0} - {1}"", name, DateTime.Now);
}
}
}
";
Console.WriteLine("{0}", DateTime.Now);
// 创建编译器对象
CSharpCodeProvider p = new CSharpCodeProvider(); // 设置编译参数
CompilerParameters options = new CompilerParameters();
options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add("test4.dll");
options.GenerateInMemory = true;
options.GenerateExecutable = false;
//options.OutputAssembly = "MyTest"; // 开始编译
CodeSnippetCompileUnit cu = new CodeSnippetCompileUnit(code); CompilerResults cr = p.CompileAssemblyFromDom(options, cu); if (cr.Errors.HasErrors)
{
Console.WriteLine("编译错误:");
foreach (CompilerError err in cr.Errors)
{
Console.WriteLine(err.ErrorText);
}
Console.ReadLine();
}
else
{
// 通过反射,调用HelloWorld的实例
Assembly objAssembly = cr.CompiledAssembly;
IMyClass objHelloWorld = objAssembly.CreateInstance("MyNamespace.MyClass") as IMyClass;
MethodInfo objMI = objHelloWorld.GetType().GetMethod("Test"); Console.WriteLine(objMI.Invoke(objHelloWorld, null));
}
}
}
}
编译没问题