代码
CSharpCodeProvider CSharp = new CSharpCodeProvider();
String[] dll = { "System.dll", "System.Windows.Forms.dll" };
CompilerParameters 编译参数 = new CompilerParameters(dll);
编译参数.GenerateExecutable = false;
编译参数.GenerateInMemory = true;
string 代码串 =
"class wxd"+
"{"+
"public string setText(System.Windows.Forms.Control ct)"+
"{"+
"ct.Text = \"按钮提示文字被我修改了\";"+
"System.Windows.Forms.MessageBox.Show(\"wxwinter\");"+
"return \"ok\";"+
"}"+
"}";
CompilerResults 结果 = CSharp.CompileAssemblyFromSource(编译参数, 代码串);
Assembly 程序集 = 结果.CompiledAssembly;
object 动态对象 = 程序集.CreateInstance("wxd");
MethodInfo 方法 = 动态对象.GetType().GetMethod("setText");
object[] 参数 = { this.button1 };
object s = 方法.Invoke(动态对象, 参数);
System.Console.WriteLine(s);
String[] dll = { "System.dll", "System.Windows.Forms.dll" };
CompilerParameters 编译参数 = new CompilerParameters(dll);
编译参数.GenerateExecutable = false;
编译参数.GenerateInMemory = true;
string 代码串 =
"class wxd"+
"{"+
"public string setText(System.Windows.Forms.Control ct)"+
"{"+
"ct.Text = \"按钮提示文字被我修改了\";"+
"System.Windows.Forms.MessageBox.Show(\"wxwinter\");"+
"return \"ok\";"+
"}"+
"}";
CompilerResults 结果 = CSharp.CompileAssemblyFromSource(编译参数, 代码串);
Assembly 程序集 = 结果.CompiledAssembly;
object 动态对象 = 程序集.CreateInstance("wxd");
MethodInfo 方法 = 动态对象.GetType().GetMethod("setText");
object[] 参数 = { this.button1 };
object s = 方法.Invoke(动态对象, 参数);
System.Console.WriteLine(s);
注:
C/S环境下dll位置以当前编译路径,一般直接写“XXX.dll”即可。
B/S环境下引用的非系统dll位置需要指定绝对路径,比如:String[] dll = { "d:\SqlDataAccess.dll" };