4

我有以下继承层次结构:

A 类:表格
B 类:A 类

A 类需要能够接受一个参数,以便我可以像这样创建 B 类的实例:

ClassB mynewFrm = new ClassB(param);

如何在 A 类中定义这样的构造函数?

谢谢!

我在 .net 3.5 中使用 Winforms,c#

编辑:A 类和 B 类被定义为表单,使用部分类。所以我想这变成了一个关于部分类和自定义(覆盖)构造函数的问题。

4

3 回答 3

9

这是一个完整的演示示例,演示了所需的行为。

为了方便您的学习,我选择了一个字符串类型参数,您可以根据自己的情况进行调整。

要对其进行测试,请创建一个新的Visual Studio * C# * 项目并使用以下代码填充program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Stackoverflow
{

    public class ClassA : Form
    {
        public ClassA()
        {
            InitializeComponent();
        }

        public ClassA(string WindowTitleParameter)
        {
            InitializeComponent();
            this.Text = WindowTitleParameter;
            MessageBox.Show("Hi! I am ClassB constructor and I have 1 argument. Clic OK and look at next windows title");
        }

        private void InitializeComponent() // Usually, this method is located on ClassA.Designer.cs partial class definition
        {
            // ClassA initialization code goes here
        }

    }

    public class ClassB : ClassA
    {
        // The following defition will prevent ClassA's construtor with no arguments from being runned
        public ClassB(string WindowTitleParameter) : base(WindowTitleParameter) 
        {
            InitializeComponent();
            //this.Text = WindowTitleParameter;
            //MessageBox.Show("Hi! I am ClassB constructor and I have 1 argument. Clic OK and look at next windows title");
        }

        private void InitializeComponent() // Usually, this method is located on ClassA.Designer.cs partial class definition
        {
            // ClassB initialization code goes here
        }

    }

    static class Program
    {
        /// <summary> 
        /// The main entry point for the application. 
        /// </summary> 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // If you debug this code using StepInto, you will notice that contructor of ClassA (argumentless)
            // will run prior to contructor of classB (1 argument)

            Application.Run(new ClassB("Look at me!"));
        }
    }
}
于 2012-10-05T22:03:32.370 回答
0

对于ClassA您的构造函数看起来像

public ClassA(Object param)
{
    //...
}

因为ClassB它看起来像

public ClassB(Object param) : base(param) 
{
    //...
}

wherebase(param)实际上将调用ClassA接受该参数的构造函数。

于 2012-10-05T21:03:52.007 回答
0

类的构造函数看起来像这样。

private Object _object1;

public ClassA(object object1)
{
    _object1 = object1;
}
于 2012-10-05T21:02:04.770 回答