我正试图编译文本文件中的代码,以更改WinForms应用程序主窗体上文本框中的值。也就是说,在调用窗体中添加另一个带有方法的分部类。表单有一个按钮(按钮1)和一个文本框(文本框1)。
文本文件中的代码是:
this.textbox 1.text=“你好,世界!!
代码:
namespace WinFormCodeCompile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Load code from file
StreamReader sReader = new StreamReader(@"Code.txt");
string input = sReader.ReadToEnd();
sReader.Close();
// Code literal
string code =
@"using System;
using System.Windows.Forms;
namespace WinFormCodeCompile
{
public partial class Form1 : Form
{
public void UpdateText()
{" + input + @"
}
}
}";
// Compile code
CSharpCodeProvider cProv = new CSharpCodeProvider();
CompilerParameters cParams = new CompilerParameters();
cParams.ReferencedAssemblies.Add("mscorlib.dll");
cParams.ReferencedAssemblies.Add("System.dll");
cParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
cParams.GenerateExecutable = false;
cParams.GenerateInMemory = true;
CompilerResults cResults = cProv.CompileAssemblyFromSource(cParams, code);
// Check for errors
if (cResults.Errors.Count != 0)
{
foreach (var er in cResults.Errors)
{
MessageBox.Show(er.ToString());
}
}
else
{
// Attempt to execute method.
object obj = cResults.CompiledAssembly.CreateInstance("WinFormCodeCompile.Form1");
Type t = obj.GetType();
t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, null);
}
}
}
}
当我编译代码时,compilerResults返回一个错误,指出winformcodecompile.form1不包含textbox 1的定义。
有没有一种方法可以动态地为调用程序集创建另一个分部类文件并执行该代码?
我想我错过了一些非常简单的东西。