问题
I'm attempting to compile code in a text file to change a value in a TextBox on the main form of a WinForms application. Ie. add another partial class with method to the calling form. The form has one button (button1) and one TextBox (textBox1).
The code in the text file is:
this.textBox1.Text = "Hello World!!";
And the code:
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);
}
}
}
}
When I compile the code, the CompilerResults returns an error that says WinFormCodeCompile.Form1 does not contain a definition for textBox1.
Is there a way to dynamically create another partial class file to the calling assembly and execute that code?
I assume I'm missing something really simple here.
回答1:
Partial classes can't span assemblies - assembly is the unit of compilation, and partial classes become a single class once compiled (there's no equivalent concept on CLR level).
回答2:
You could try using parameters to pass the object you want to manipulate, like:
// etc
public void UpdateText(object passBox)
{" + input + @" }
// more etc
t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, new object[] { this.textbox });
So that way the snippet would result as:
(passBox as TextBox).Text = "Hello World!!";
来源:https://stackoverflow.com/questions/2703439/codedom-compile-partial-class