创建对象时,将自动调用C#中的构造方法。构造函数与类具有相同的名称,例如-
public class Department { public Department () { Console.WriteLine("Default Constructor! "); } }
以下是显示C#中构造函数用法的代码。
using System; public class Department { public Department () { Console.WriteLine("Constructor Invoked"); } public static void Main(string[] args) { Department dept1 = new Department (); } }
输出结果
Constructor Invoked