传递参数在Form构造函数中,winforms c# [英] Passing parameters in the Form constructor, winforms c#
问题描述
我有以下继承层次结构:
I have a following inheritance hierarchy:
A类:FormÚ
B类:A类
Class A : Form
Class B : Class A
A类需要能够接受一个参数,这样我可以这样创建B类的实例:
Class A needs to be able to accept a parameter so that I can create the instance of Class B like this:
ClassB mynewFrm = new ClassB(param);
如何在A类中定义这样的构造函数?
How do I define such a constructor in Class A?
感谢!
我在.NET 3.5中使用Winforms,c#
I am using Winforms in .net 3.5, c#
b $ b A类和B类使用部分类定义为表单。
所以我猜这是一个关于部分类和自定义(覆盖)构造函数的问题。
EDITED: Class A and Class B are defined as forms, using partial classes. So I guess this is turning into a question about partial classes and custom (overriden) constructors.
推荐答案
为了方便您的学习,我选择了一个字符串类型参数,您可以根据自己的需要调整
For the sake of ease your learning, I chose a string type parameter that you adjust to your case.
要测试它,请创建一个新的 Visual Studio * C# *项目并填写 .cs 与以下代码
To test it, create a new Visual Studio *C#* project and fill program.cs with the following code
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!"));
}
}
}
这篇关于传递参数在Form构造函数中,winforms c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!