C# 构造函数
C# 构造函数
在 C# 中,构造函数是一种特殊的方法,在创建对象时会自动调用。一般用于初始化新对象的数据成员。 C# 中的构造函数与 class 或 struct 同名。
C# 中可以有两种类型的构造函数。
默认构造函数
参数化构造函数
C# 默认构造函数
没有参数的构造函数称为默认构造函数。
C# 默认构造函数示例: 在类中包含 Main()
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();
}
}
输出:
default Constructor Invoked
default Constructor Invoked
C# 默认构造函数示例: 在另一个类中使用 Main()
让我们看看默认构造函数的另一个示例,其中我们在另一个类中使用 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();
}
}
输出:
default Constructor Invoked
default Constructor Invoked
C# 参数化构造函数
具有参数的构造函数称为参数化构造函数。它用于为不同的对象提供不同的值。
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 890000
102 Mahesh 490000