我的课程A
继承自UserControl
:
public class A : UserControl
{
private Form1 _form; // class Form1 : Form { //... }
private A()
{
InitializeComponent();
}
public A(Form1 form) : this()
{
_form = form;
}
}
可视代码设计器创建代码:
private void InitializeComponent()
{
this.a = new A((Form1)this); // here I myself added foo object in ctor
//...
}
private A a;
我有一个错误:
Warning 1 Type 'A' does not have a constructor with parameters of types Form. 0 0
我做错了什么?以及如何避免这种情况?
修改
问题是我需要知道在ctor中对父(我的情况Form1
)的引用,我不能使用.Parent
属性,因为.Parent
属性直到之后才设置完成了ctor,这就是为什么我选择了这种错综复杂的方式来通过ctor中的父母。
问题尚未解决
答案 0 :(得分:0)
你几乎回答了自己的问题。
问题是我需要知道在ctor中引用父(在我的情况下是Form1),我不能使用.Parent属性,因为直到ctor完成后才设置.Parent属性,这就是为什么我有选择这种错综复杂的方式来传递ctor中的父母。
从Form1的构造函数调用InitializeComponent方法,在InitializeComponent中尝试获取对“this”的引用。我认为问题是'this'尚未创建(因为你仍然在它的构造函数中)。
正如有人已经提到的,处理它的一种方法是使用接口。
public class A : UserControl
{
private MyInterface _myInterface;
private A()
{
InitializeComponent();
}
public A(MyInterface myInterface) : this()
{
_myInterface = myInterface;
}
}
然后让你的表单实现界面。