我试图在文本文件中编译代码,以在TextBox应用程序的主要形式上更改WinForms中的值。即。向调用窗体添加另一个具有方法的分部类。表单有一个按钮(button1)和一个TextBox (textBox1)。
文本文件中的代码是:
World.textBox1.Text= "Hello!!“
守则如下:
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的定义。
是否有方法动态地为调用程序集创建另一个部分类文件并执行该代码?
我想我错过了一些很简单的东西。
发布于 2010-04-24 06:22:09
部分类不能跨越程序集-程序集是编译的单元,部分类一旦编译就变成了一个类(在CLR级别上没有等效的概念)。
发布于 2010-04-24 06:38:06
您可以尝试使用参数传递要操作的对象,例如:
// etc
public void UpdateText(object passBox)
{" + input + @" }
// more etc
t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, new object[] { this.textbox });这样,代码片段就会产生如下结果:
(passBox as TextBox).Text = "Hello World!!";https://stackoverflow.com/questions/2703439
复制相似问题