在 C# 中,构造函数是一种特殊方法,在创建对象时会自动调用。一般用于初始化新对象的数据成员。C# 中的构造函数与类或结构同名。
C# 中可以有两种类型的构造函数。
默认构造函数
参数化构造函数
没有参数的构造函数称为默认构造函数。它在创建对象时调用。
using System;
public class Employee
{
public Employee()
{
Console.WriteLine("调用的默认构造函数");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
}
}输出:
调用的默认构造函数 调用的默认构造函数
让我们看看另一个默认构造函数的例子,我们在另一个类中有 Main() 方法。
using System;
public class Employee
{
public Employee()
{
Console.WriteLine("调用的默认构造函数");
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
}
}
输出:
调用的默认构造函数 调用的默认构造函数
有参数的构造函数称为参数化构造函数。它用于为不同的对象提供不同的值。
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();
}
}
输出:
101 Sonoo 890000102 Mahesh 490000