Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

c# - How to avoid error "Constructor on type 'MyType' not found" when inheriting a base class

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.

Example:

public partial class BaseForm : Form
{
    public BaseForm(int number)
    {
        InitializeComponent();
    }
}

public partial class ChildForm : BaseForm
{
    public ChildForm(int number)
        : base(number)
    {
        InitializeComponent();
    }
}

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:

Constructor on type 'MyProject.BaseForm' not found.

Note: regardless of the error, the project compiles and runs fine.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That is completely impossible.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...