有没有什么方法可以在后代类构造函数的末尾调用超级构造函数?
它适用于Java,但在C#中,关键字base似乎不等同于Java的超级.
例:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
不,使用base关键字的概念或者Constructor Initializer是首先调用基础构造函数然后是子构造函数.因此,首先初始化子节点上的所有公共或共享参数,然后初始化子类的特定属性.这也是一个abstract类可以拥有Constructor 的原因之一
无法将调用推迟到基本构造函数,它必须在派生构造函数启动之前完成。
但是,可以在传递基本构造函数之前通过提供传递给基本表达式的表达式来在派生构造函数外部执行计算:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
上面有些棘手:使用带有一对int的私有构造函数将这些int转发给基本构造函数。元组在GenTuple方法内部生成,在调用base构造函数之前会被调用。