我有一个简单的 Windows 应用程序,其中创建了一个动态 Win Form 并与工具箱一起显示。用户在这个动态创建的表单上拖放控件并相应地编写代码。下面不是完整的代码,而是我面临问题的部分。我正在尝试编译用户在运行时编写的代码,但它给了我错误“在表单 0 -> 当前上下文中不存在名称 'InitializeComponent' 第 (12) 行错误:CS0103”
// small piece of code
string SecondLine = @"public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}";
Form1 frm =new Form1();
frm.textBox1.Text = "using System;" + Environment.NewLine
+ "using System.IO;" + Environment.NewLine + "using System.Drawing;" + Environment.NewLine + "using System.Windows.Forms;" + Environment.NewLine + Environment.NewLine + "namespace MiniCompiler{" + Environment.NewLine + Environment.NewLine;
frm.textBox1.Text = frm.textBox1.Text + SecondLine.ToString();
frm.textBox1.Text = frm.textBox1.Text + Environment.NewLine + Environment.NewLine + "static class Program{" + Environment.NewLine + " [STAThread] " + Environment.NewLine + "static void Main()" + "{" + Environment.NewLine;
string firstLine = "Application.EnableVisualStyles(); " + Environment.NewLine + "Application.SetCompatibleTextRenderingDefault(false);" + Environment.NewLine + "Application.Run(new Form1());";
frm.textBox1.Text = frm.textBox1.Text + Environment.NewLine + firstLine;
frm.textBox1.Text = frm.textBox1.Text.ToString() + Environment.NewLine + "}" ;
// 编译代码
CSharpCodeProvider provider = new CSharpCodeProvider();
ICodeCompiler compiler = provider.CreateCompiler();
CompilerResults result = compiler.CompileAssemblyFromSource(param,code);
我真的不确定在这里编译 Winform 有什么问题。
谢谢,