问题描述
我有一个Visual Studio 2010 Windows窗体应用程序,其中包含其他类将继承的Form基类。基类的构造函数接受子类将传递给基类的参数。
I have a Visual Studio 2010 Windows Forms app which includes a Form base class that other classes will inherit. The base class' constructor takes a parameter that the child classes will pass to the base class.
示例:
public partial class BaseForm : Form
{
public BaseForm(int number)
{
InitializeComponent();
}
}
public partial class ChildForm : BaseForm
{
public ChildForm(int number)
: base(number)
{
InitializeComponent();
}
}
我遇到的问题是,我尝试在VisualStudio的设计视图模式下打开ChildForm,我收到以下错误:
The problem that I'm running into is, when I attempt to open the ChildForm in VisualStudio's Design View mode, I receive the following error:
注意:无论错误如何,项目都会编译并运行正常。
如果我用不包含任何参数的构造函数重载构造函数,我可以避免错误。
I can avoid the error if I overload the constructor with one that does not contain any parameters.
示例:(这摆脱了错误)
Example: (This gets rid of the error)
public partial class BaseForm : Form
{
public BaseForm(int number)
{
InitializeComponent();
}
public BaseForm()
{
InitializeComponent();
}
}
public partial class ChildForm : BaseForm
{
public ChildForm(int number)
: base(number)
{
InitializeComponent();
}
}
我的问题是,如何创建基类那不包括无参数构造函数并避免设计视图错误?
My question is, how can I create a base class that does not include a parameterless constructor and avoid the Design View error?
推荐答案
这是完全不可能的。
您在设计视图中看到的表单是基类的实际实例。
如果没有默认构造函数,则设计器无法创建该实例。
The form you see in the design view is an actual instance of your base class.
If there is not default constructor, the designer cannot create that instance.
您可以使用 [Obsolete(仅限Designer,真实)]
标记构造函数,并使其抛出异常如果不在设计师时调用,以防止其他人调用它。
You can mark the constructor with the [Obsolete("Designer only", true)]
, and make it throw an exception if called when not in the designer, to prevent other people from calling it.
这篇关于如何避免错误“未找到MyType'类型上的构造函数”继承基类时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!