Inherit from the "Form", which has options

I have a form called ScanFolder , and I need another form, which should be very similar to ScanFolder , so I decided to use the form inheritance . But there seems to be a misunderstanding with the constructor.

ScanFolder as follows:

 public partial class ScanFolder : Form { public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods GMethodsClass) { //Doing something with parameters } } 

I tried to inherit Form as follows:

 public partial class Arch2 : ScanFolder { } 

But I get a Constructor warning of type 'mhmm.ScanFolder' not found, and there is also an error in Arch2 form editing mode, where I see a call stack error.

So, I tried something like this:

 public partial class Arch2 : ScanFolder { public Arch2(MainForm parent, bool[] autoModes, GlobalMethods GMethodsClass) : base(parent, autoModes, GMethodsClass) { } } 

But it is all the same.

As you can see, I obviously do not know what I am doing. I am trying to make Arch2 look like ScanFolder , so I see it in the constructor view, and also redefine some methods or event handlers.

+6
source share
2 answers

To use the form constructor, you need a parameterless constructor:

 public partial class ScanFolder : Form { public ScanFolder() { InitializeComponent(); // added by VS } public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods gm) : this() // <-- important { // don't forget to call the parameterless ctor in each // of your ctor overloads } } 

Or, if you really need to have some init parameters, you can do it the other way around:

 public partial class ScanFolder : Form { public ScanFolder() : this(null, new bool[0], new GlobalMethods()) { } public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods gm) { InitializeComponent(); // added by VS // other stuff } } 

I recommend the first approach, otherwise you need to pass some reasonable parameters to the default (I do not recommend passing a null parameter).

It seems that in some cases, you will also have to restart Visual Studio after changing the class.

+13
source

You can use this code in parent form:

 public partial class ScanFolder : Form { public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods GMethodsClass) { //doing something with parameters } } 

and then in child form:

 public partial class ScanFolder : Form { public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods GMethodsClass) : base(parent,autoModes,GMethodsClass) { //doing something with parameters } } 
+1
source

Source: https://habr.com/ru/post/886306/


All Articles