本文介绍了从“形式”具有参数继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 ScanFolder 表格,我需要另一种形式,需要非常类似于 ScanFolder ,所以我决定用形式继承。但是,似乎与构造一些误解。

I have a Form named ScanFolder, and I need another Form, that needs to be very similar to ScanFolder, so I decided to use form inheritance. But there seems to be some misunderstanding with the constructor.

ScanFolder 是这样的:

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

我想继承表格是这样的:

public partial class Arch2 : ScanFolder
{
}

但我得到警告构造上键入mhmm.ScanFolder没有找到,也没有对 Arch2错误表格编辑模式,在这里我看到调用堆栈错误

But I get warning Constructor on type 'mhmm.ScanFolder' not found, and also there is an error on Arch2 Form edit mode, where I see a call stack error.

所以,我想是这样的:

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

但它仍是相同的。

But it is still the same.

正如你所看到的,我明明没有任何想法,我在做什么。我试图做到的,是让 Arch2 看起来一样的 ScanFolder ,这样我就可以看到它的设计师视图,还覆盖某些方法或事件处理程序。

As you can see, I clearly don't have any idea what I'm doing. What I'm trying to achieve is getting Arch2 to look the same as ScanFolder, so I can see it in designer view and also override some methods or event handlers.

推荐答案

要使用窗体设计器,你将需要有一个参数的构造函数:

To use the Forms designer, you will need to have 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 params, 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 default parameters (I don't recommend passing a null parameter).

这篇关于从“形式”具有参数继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:37