C# 初始化类成员变量的两种方式的对比

类成员变量可以在声明的时候就赋值,或者在构造函数里面再进行赋值,那么声明时赋值操作和构造函数哪个先被调用呢?我们用如下的测试代码进行测试。

public class Base 
{
    private int x = BaseInitializer();

    public Base()
    {
        Debug.Log("Base ctor");
    }

    private static int BaseInitializer()
    {
        Debug.Log("BaseInitializer");
        return 0;
    }
}

public class Derived : Base
{
    private int x = DerivedInitializer();

    public Derived() 
    {
        Debug.Log("Derived ctor");
    }

    private static int DerivedInitializer()
    {
        Debug.Log("DerivedInitializer");
        return 0;
    }
}

输出结果为:

DerivedInitializer
BaseInitializer
Base ctor
Derived ctor

测试结果表明,声明时的赋值操作要先于构造函数执行。