所以我在 C# 中创建了一个库存系统,其中每个项目都是一个从其他类继承的类。目前我正在研究一些测试类,其中之一是 Fish。 Fish 继承自 Consumables,Consumables 继承自 Items(顶级类) 注意:消耗品基本上是可堆叠的元素。
我想在 Consumables 类中创建 2 个默认构造函数,一个不带参数:
public Consumable() : base() {
quantity = 1;
}
只需将数量设置为 1。
还有一个接受一个参数的数量:
public Consumable(int Quantity) : this() {
if (quantity <= maxStack)
quantity = Quantity;
else
quantity = maxStack;
}
在创建时设置数量。现在我认为在上面的代码中使用 this() 会强制 child 使用它自己的默认无参数构造函数作为 this,但事实并非如此。这就是我对鱼的看法:
public Fish() : base() {
name = "fish";
ID = 1;
variant = 0;
maxStack = 20;
desc = "A Fish of some kind";
rarity = ItemRarity.Common;
}
public Fish(int QTY) : base(QTY) { }
我想要发生的是当调用 Fish(int QTY) 时,我希望它调用 Fish() 来设置基础知识,然后调用 Consumable(QTY) 来设置数量。
但是目前,当调用 Fish(int QTY) 时,它会调用 Consumable(QTY),后者调用 Consumable() 而不是 Fish()
有什么方法可以让它按照我想要的方式工作吗?
最佳答案
编辑:正如一些评论中已经建议的那样,这里有一个可能的解决方案,它具有从两个构造函数调用的初始化方法。 Fish(qty) 现在调用基础构造函数和自己的 Init 方法(与 Fish() 相同)。
public Fish() : base() {
Init();
}
public Fish(int QTY) : base(QTY){
Init();
}
private void Init(){
name = "fish";
ID = 1;
variant = 0;
maxStack = 20;
desc = "A Fish of some kind";
rarity = ItemRarity.Common;
}
关于c# - 在继承中使用 this() 和 base(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41647949/