有什么方法可以在子类构造函数的末尾调用 super 构造函数吗?
它在 Java 中有效,但在 C# 中,关键字 base
似乎并不等同于 Java 的 super。
例子:
class CommonChest : BasicKeyChest
{
public CommonChest()
{
Random rnd = new Random();
int key = rnd.Next(1, 6);
int coins = rnd.Next(70, 121);
super(key, coins, "Common");
}
}
最佳答案
没有办法推迟对基础构造函数的调用,它必须在派生构造函数开始之前完成。
但是,您可以在调用基础构造函数之前通过提供传递给基础的表达式在派生构造函数之外执行计算:
class CommonChest : BasicKeyChest {
public CommonChest()
: this(GenTuple()) {
}
private CommonChest(Tuple<int,int> keysCoins)
: base(keysCoins.Item1, keysCoins.Item2, "Common") {
}
private static Tuple<int,int> GenTuple() {
Random rnd = new Random();
int keys = rnd.Next(1, 6);
int coins = rnd.Next(70, 121);
return Tuple.Create(keys, coins);
}
}
上面的内容有点棘手:采用一对整数的私有(private)构造函数用于将这些整数转发给基本构造函数。元组在 GenTuple
方法中生成,该方法在调用 base
构造函数之前被调用。
关于c# - 在调用基本构造函数之前计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42694927/