在C#中,构造函数是在创建对象时自动调用的特殊方法。一般用于初始化新对象的数据成员。C#中的构造函数与class或struct同名。
在C#中可以有两种类型的构造函数。
没有参数的构造函数称为默认构造函数。它在创建对象时调用。
using System; public class Employee { public Employee() { Console.WriteLine("Default Constructor Invoked"); } public static void Main(string[] args) { Employee e1 = new Employee(); Employee e2 = new Employee(); } }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-constructor.html
来源:LearnFk无涯教程网
Default Constructor Invoked Default Constructor Invoked
让无涯教程看看默认构造函数的另一个示例,其中在另一个类中使用main()方法。
using System; public class Employee { public Employee() { Console.WriteLine("Default Constructor Invoked"); } } class TestEmployee{ public static void Main(string[] args) { Employee e1 = new Employee(); Employee e2 = new Employee(); } }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-constructor.html
来源:LearnFk无涯教程网
Default Constructor Invoked Default Constructor Invoked
具有参数的构造函数称为参数化构造函数。它用于为不同的对象提供不同的值。
using System; public class Employee { public int id; public String name; public float salary; public Employee(int i, String n,float s) { id = i; name = n; salary = s; } public void display() { Console.WriteLine(id + " " + name+" "+salary); } } class TestEmployee{ public static void Main(string[] args) { Employee e1 = new Employee(101, "Sonoo", 890000f); Employee e2 = new Employee(102, "Mahesh", 490000f); e1.display(); e2.display(); } }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-constructor.html
来源:LearnFk无涯教程网
101 Sonoo 890000 102 Mahesh 490000
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)