📅  最后修改于: 2023-12-03 15:30:19.468000             🧑  作者: Mango
C#构造函数是指在创建类的新实例时,自动调用的特殊方法。构造函数的主要任务是初始化类的实例及其任何字段和属性,以确保该对象在创建时处于可预测状态。
访问修饰符 类名([参数列表])
{
//构造函数体
}
public class Person
{
private string name;
private int age;
//无参构造函数
public Person()
{
name = "Tom";
age = 18;
}
//有参构造函数
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
}
static void Main(string[] args)
{
Person p1 = new Person();
Console.WriteLine("Name: " + p1.Name + ", Age: " + p1.Age);
Person p2 = new Person("John", 20);
Console.WriteLine("Name: " + p2.Name + ", Age: " + p2.Age);
}
构造函数可以被重载,以支持不同的构造方式。我们可以按照以下方式来定义重载构造函数:
public class MyClass
{
private int x;
//无参构造函数
public MyClass()
{
x = 0;
}
//有参构造函数1
public MyClass(int x)
{
this.x = x;
}
//有参构造函数2
public MyClass(int x, int y)
{
this.x = x + y;
}
}
在继承链中,构造函数的执行顺序是从最顶层基类开始,一直到最底层派生类。以下是构造函数执行顺序的示例:
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass: Constructor");
}
public BaseClass(int x)
{
Console.WriteLine($"BaseClass: Constructor with {x}");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass() : base()
{
Console.WriteLine("DerivedClass: Constructor");
}
public DerivedClass(int x) : base(x)
{
Console.WriteLine($"DerivedClass: Constructor with {x}");
}
}
static void Main(string[] args)
{
DerivedClass dc1 = new DerivedClass();
Console.WriteLine("------------------------");
DerivedClass dc2 = new DerivedClass(100);
}
输出:
BaseClass: Constructor
DerivedClass: Constructor
------------------------
BaseClass: Constructor with 100
DerivedClass: Constructor with 100
C#构造函数是类的特殊成员,用于初始化类的实例及其任何字段和属性。构造函数可以被重载,并且有不同的调用方法。在继承链中,构造函数的执行顺序是从最顶层基类开始,一直到最底层派生类。