C#中的构造函数和继承问题

dev*_*ium 7 c# inheritance constructor

我有以下问题:

public class A {
    public A(X, Y, Z) {
    ...
    }
}

public class B : A {
    public B(X, Y) : base(X, Y) {
        //i want to instantiate Z here and only then pass it to the base class!
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?有办法吗?

Ani*_*Ani 13

常见的解决方案是调用属于可以计算要传递给基础构造函数的参数值的类型的静态方法.

例如:

public B(int x, int y)
    : base(x, y, CalculateZ(x, y))
{

}

// You can make this parameterless if it does not depend on X and Y
private static int CalculateZ(int x, int y)
{
   //Calculate it here.

    int exampleZ = x + y;

    return exampleZ;
}
Run Code Online (Sandbox Code Playgroud)

请注意,这CalculateZ不能是实例方法,因为this引用在构造函数初始值设定项中不可用.

从语言规范10.11.1构造函数初始化器:

实例构造函数初始值设定项无法访问正在创建的实例.因此,在构造函数初始值设定项的参数表达式中引用它是一个编译时错误,因为参数表达式通过简单名称引用任何实例成员的编译时错误.

编辑:在说明中将"实例"更改为"静态".