Ini*_*eer 3 c# reflection codedom
我正在尝试在文本文件中编译代码以更改WinForms应用程序主窗体上的TextBox中的值.IE浏览器.使用方法向调用表单添加另一个partial类.表单有一个按钮(button1)和一个TextBox(textBox1).
文本文件中的代码是:
this.textBox1.Text ="Hello World !!";
和代码:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译代码时,CompilerResults返回一个错误,指出WinFormCodeCompile.Form1不包含textBox1的定义.
有没有办法动态创建另一个部分类文件到调用程序集并执行该代码?
我想我在这里错过了一些非常简单的东西.