0

我有一个用户控件(section1),我需要传递对我的主窗体(Form1)的引用。问题是每当我将表单作为参数传递给 section1 的构造函数时,它都会破坏设计器并且我得到一个错误:

 Type 'M.section1' does not have a constructor with parameters of types Form.    

 The variable 's1' is either undeclared or was never assigned.  

Form1.Designer.cs

 this.s1 = new M.section1(this); // this is the line that causes the problem

section1.cs用户控件

public partial class section1 : UserControl
{
    private Form1 f { get; set; }

    public section1(Form1 frm) // constructor 
    {
         f = frm;
    }
}

奇怪的是,即使当我在设计器中打开 Form1 时,它也给了我错误,它编译得很好,并且引用确实有效,我可以从用户控件访问 Form1。有什么建议么?谢谢!

4

2 回答 2

1

Designer 使用反射来创建控件的实例。因此,您需要一个默认构造函数 - 这就是它要寻找的。

public partial class section1 : UserControl
{
    private Form1 f { get; set; }

    public section1() // designer calls this
    {
        InitializeComponent(); //I hope you haven't forgotten this
    }

    public section1(Form1 frm) : this() //call default from here : at runtime
    {
         f = frm;
    }
}
于 2013-06-15T15:46:13.787 回答
0

我一直使用的解决方案是使用默认构造函数或向参数添加默认nullfrm

public section1(Form1 frm = null)
{
    f = frm;
}

您可能需要在null这里和那里添加一些检查。

于 2013-06-15T10:46:34.540 回答