1

我有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。

问题还没有解决

4

1 回答 1

0

你几乎已经回答了你自己的问题。

问题是我需要知道 ctor 中对父级(在我的情况下为 Form1)的引用,我不能使用 .Parent 属性,因为 .Parent 属性直到 ctor 完成后才设置,这就是我选择这个令人费解的原因在ctor中传递父级的方法。

InitializeComponent 方法是从 Form1 的构造函数中调用的,在 InitializeComponent 中,您试图获取对“this”的引用。我认为问题是“这个”还没有被创建(因为你还在它的构造函数中)。

正如有人已经提到的,处理它的一种方法是使用接口。

public class A : UserControl
{
  private MyInterface _myInterface; 

  private A() 
  {
      InitializeComponent();
  }

  public A(MyInterface myInterface) : this() 
  {
     _myInterface = myInterface;
  }
}

然后让你的表单实现接口。

于 2012-12-21T06:33:39.797 回答