C#中的构造函数也可以应用方法重载。C#中有默认构造函数,也可以定义带参数的构造函数。构造函数必须与类同名,并且不能有返回值。所以C#构造函数重载相当于不同数量的参数方法重载。
using System; class Animal { public string _name; public string _color; public int _speed; public Animal() { this._speed = 30; } public Animal(string name, string color) { this._name = name; this._color = color; } public Animal(string name, string color, int speed) { this._name = name; this._color = color; this._speed = speed; } }
class Program { static void Main(string[]args) { //方法一 Animal animal1 = new Animal(); animal1._name = "兔子"; animal1._color = "灰色"; //animal1._speed = 40; Console.WriteLine( "调用默认构造函数输出动物为{0},颜色为{1},奔跑速度为{2}km/h",
animal1._name, animal1._color, animal1._speed); //方法二 Animal animal2 = new Animal("狗", "黄色"); Console.WriteLine("调用两个参数构造函数输出动物为{0},颜色为{1}", animal2._name, animal2._color); //方法三 Animal animal3 = new Animal("花猫", "白色", 20); Console.WriteLine( "调用三个参数构造函数输出动物为{0},颜色为{1},奔跑速度为{2}", animal3._name, animal3._color, animal3._speed); Console.WriteLine("一只" + animal3._color + "的" + animal3._name + "正在以" + animal3._speed + "km/h的速度在奔跑/n");
Console.ReadLine();
} }
我们再看一个例子:
using System; class Program { private string _name; private int _age; private string _qualification; public Program() { _age = 18; } public Program(string name, int age, string qualification) { this._name = name; this._age = age; this._qualification = qualification; }
static void Main() { Program p = new Program(); Console.WriteLine("默认构造函数输出年龄为" + p._age); Program p1 = new Program("李公", 19, "大学"); Console.WriteLine("参数构造函数输出姓名为" + p1._name + ",年龄为" + p1._age + ",文化程度为" + p1._qualification); } }