在 C# Windows Forms 中,重载窗体构造函数与重载普通类的构造函数类似:
public partial class Form1 : Form {
// 无参构造函数
public Form1()
{ InitializeComponent(); } // 一个参数的构造函数
public Form1(string title) : this() // 调用无参构造函数
{ this.Text = title; // 设置窗体标题 } // 两个参数的构造函数
public Form1(string title, int width) : this(title) // 调用一个参数的构造函数 { this.Width = width; // 设置窗体宽度 } }
在这个例子中:
Form1()是无参构造函数,调用InitializeComponent()初始化窗体。Form1(string title)是一个参数的构造函数,它调用无参构造函数,并设置窗体标题。Form1(string title, int width)是两个参数的构造函数,它调用一个参数的构造函数,并设置窗体宽度。