大家都知道C#构造函数主要用来设置类中属性的初始值,但经常会忽视类的构造方法也可以象方法一样引用调用父类中的构造方法或本身的其他构造方法。往往因此写了很多重复代码。下面的代码介绍了类的构造方法的几种用法。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace practise1 { class Program { static void Main(string[] args) { TestCon con = new TestCon(); Console.WriteLine(con.ToString()); TestA testA1 = new TestA(); Console.WriteLine("测试类A无参数构造方法"); Console.WriteLine(testA1.ToString()); Console.WriteLine(); TestA testA2 = new TestA("Set First Param"); Console.WriteLine("测试类A一个参数构造方法"); Console.WriteLine(testA2.ToString()); Console.WriteLine(); TestB testB1 = new TestB(); Console.WriteLine("测试类B无参数构造方法"); Console.WriteLine(testB1.ToString()); Console.WriteLine(); TestB testB2 = new TestB("Set First Param"); Console.WriteLine("测试类B一个参数构造方法"); Console.WriteLine(testB2.ToString()); Console.WriteLine(); TestB testB3 = new TestB("Set First Param", "Set Second Param"); Console.WriteLine("测试类B两个参数构造方法"); Console.WriteLine(testB3.ToString()); Console.WriteLine(); TestB testB4 = new TestB("Set First Param", "Set Second Param", "Set Third Param"); Console.WriteLine("测试类B三个参数构造方法"); Console.WriteLine(testB4.ToString()); Console.WriteLine(); Console.ReadLine(); } class TestCon { private string _a = "_a1"; private string _b = "_b2"; } /// <summary> /// 测试类A /// </summary> class TestA { protected string _testValueA; /// <summary> /// 无参数构造方法 /// </summary> public TestA() : this("Set First Param") { } /// <summary> /// 一个参数构造方法 /// </summary> /// <param name="value"></param> public TestA(string value) { _testValueA = value; } /// <summary> /// 重新ToString方法 /// </summary> /// <returns></returns> public override string ToString() { return this._testValueA; } } /// <summary> /// 测试类TestB,从TestA类中继承 /// </summary> class TestB : TestA { protected string _testValueB; protected string _testValueC; /// <summary> /// 调用父类中的构造方法 /// </summary> public TestB() : base() { this._testValueB = "Set Second Param"; this._testValueC = "Set Third Param"; } /// <summary> /// 调用父类中的构造方法 /// </summary> /// <param name="valueA"></param> public TestB(string valueA) : base(valueA) { this._testValueB = "Set Second Param"; this._testValueC = "Set Third Param"; } /// <summary> /// 调用其他构造方法 /// </summary> /// <param name="valueA"></param> /// <param name="valueB"></param> public TestB(string valueA, string valueB) : this(valueA, valueB, "Set Third Param") { } /// <summary> /// 三个参数的构造方法 /// </summary> /// <param name="valueA"></param> /// <param name="valueB"></param> /// <param name="valueC"></param> public TestB(string valueA, string valueB, string valueC) { this._testValueA = valueA; this._testValueB = valueB; this._testValueC = valueC; } /// <summary> /// 重新ToString方法 /// </summary> /// <returns></returns> public override string ToString() { return this._testValueA + "\n" + this._testValueB + "\n" + this._testValueC; } } } }
时间: 2024-10-25 13:46:16