问题描述
有什么方法可以在后代类构造函数的末尾调用超级构造函数?
Is there any way in which you can call super constructor at the end of descendant class constructor?
它可以在Java中使用,但是在C#中,关键字base
似乎并不等同于Java的super.
It works in Java, but in C# the keyword base
doesn't seem to be equivalent to Java's 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");
}
}
推荐答案
无法将调用推迟到基本构造函数,它必须在派生构造函数启动之前完成.
There is no way to postpone the call to the base constructor, it must complete before the derived constructor starts.
但是,您可以在传递基本构造函数之前通过提供传递给基本表达式的表达式来在派生构造函数外部执行计算:
However, you can perform computations outside the derived constructor prior to calling the base constructor by providing an expression that you pass to the base:
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);
}
}
上面的代码有些棘手:使用带有一对int的私有构造函数将这些int转发给基本构造函数.元组在GenTuple
方法内部生成,在 调用base
构造函数之前被调用.
The above is a little tricky: a private constructor that takes a pair of ints is used to forward these ints to the base constructor. The tuple is generated inside GenTuple
method, which is invoked before calling the base
constructor.
这篇关于在调用基本构造函数之前计算值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!