c# 继承构造函数调用顺序
构造函数
构造函数是类中的一种特殊方法,与类同名,没有返回类型。
我们可以在一个类中拥有多个构造函数(参数化构造函数/复制构造函数/静态构造函数/私有构造函数)。
当我们创建一个没有构造函数的类时,编译器会自动创建一个类的默认构造函数。
例子
public class Animal
{
public Animal()
{
Console.WriteLine("I am a constructor");
}
}
使用继承调用的构造函数的顺序
使用非静态构造函数?
在创建类的对象时,会自动调用该类的默认构造函数来初始化该类的成员。
在继承的情况下,如果我们创建子类的对象,那么将在子类构造函数之前调用父类构造函数。
即构造函数调用顺序将从上到下。
例子
public class Animal
{
public Animal()
{
Console.WriteLine("I am animal constructor.");
}
}
public class Dog : Animal
{
public Dog()
{
Console.WriteLine("I am dog constructor.");
}
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Console.Read();
}
}
输出
正如我们在输出中看到的那样,Animal 类(Base 类)的 构造函数在 Dog 类(Child)之前被调用。
但为什么?
因为当我们将一个类继承到另一个调用中时,子类可以访问基类的所有功能(私有成员除外)。
所以如果在子类的初始化过程中可能会用到父类的成员。
这就是为什么首先调用基类的构造函数来初始化所有继承的成员。
使用静态构造函数?
在静态构造函数的情况下,调用顺序将与非静态相反,即它会从下到上调用。
例子
public class Animal
{
static Animal()
{
Console.WriteLine("I am animal constructor.");
}
}
public class Dog : Animal
{
static Dog()
{
Console.WriteLine("I am dog constructor.");
}
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Console.Read();
}
}
输出
这里子类(Dog)构造函数在父类(Animal)构造函数之前被调用。
概括
在本文中,我们了解到非静态构造函数的调用顺序是自上而下,而静态构造函数的调用顺序是自下而上。
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!