创建对象时,将自动调用C#中的构造方法。构造函数与类具有相同的名称,例如,−
public class Department { public Department () { Console.WriteLine("Default Constructor! "); } }
以下是显示C#中默认构造函数用法的代码。创建对象后,构造函数立即调用-
Department dept1 = new Department ();
默认构造函数是不带参数的构造函数,例如-
Department () { }
让我们看完整的示例,以学习如何使用默认构造函数-
using System; public class Department { public Department () { Console.WriteLine("Constructor Invoked"); } public static void Main(string[] args) { //对象 Department dept1 = new Department (); } }
输出结果
Constructor Invoked