3

我有一个简单的 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 有什么问题。

谢谢,

4

1 回答 1

1

我认为错误信息是正确的。我看不到您的 InitializeComponent()-Method(在 Form1-Class 的构造函数中调用女巫)是在哪里定义的。

因为 Form 是作为部分类生成的,所以可能有(实际上默认情况下有)多个文件,其中包含该类的成员。默认情况下,您有两个文件。在您的情况下,Form1.cs 和 Form1.Designer.cs。两者一起描述了 Form1 类。

方法 InitializeComponent 不被继承。它在同一个类中定义,只是在另一个文件中。

    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.Text = "Form1";
    }

您可以将此方法从 Form1-Class 的其他部分复制到您的 SecondLine-String 中。然后它应该工作,我想。

看这个文件

于 2014-09-25T09:41:04.827 回答