我正在尝试编译文本文件中的代码以更改 WinForms 应用程序主窗体上的 TextBox 中的值。 IE。将另一个带有方法的分部类添加到调用表单中。该表单有一个按钮 (button1) 和一个文本框 (textBox1)。
文本文件中的代码是:
this.textBox1.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 不包含 textBox1 的定义。
有没有办法动态地为调用程序集创建另一个部分类文件并执行该代码?
我想我在这里遗漏了一些非常简单的东西。
分部类不能跨越程序集 - 程序集是编译的单位,分部类一旦编译就成为单个类(CLR 级别上没有等效的概念)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)