gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:57:40 25 4
gpt4 key购买 nike

我遇到了以下问题:

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!
}
}

我该如何解决这个问题?有办法吗?

最佳答案

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

例如:

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;
}

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

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

An instance constructor initializer cannot access the instance being created. Therefore it is a compile-time error to reference this in an argument expression of the constructor initializer, as is it a compile-time error for an argument expression to reference any instance member through a simple-name.

编辑:将描述中的“实例”更改为“静态”。

关于c# - C#中的构造函数和继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4213705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com