c# - 在继承中使用 this() 和 base()

标签 c# inheritance unity3d this radix

所以我在 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/

相关文章:

c# - 无法进入返回 IEnumerable<T> 的方法?

c# - 我如何更改 CSVHelper 中的字段顺序和字段名称

c# - 无法转换 COM 对象

scala - 在 Scala 的父特性中声明子特性的 self 类型

c# - Unity Nav Mesh Agent 目的地无效?

c# - NET 6.0应用程序: Serilog exception on startup when trying to log to Azure Application Insights

typescript 声明 : Merge a class and an interface

Java-JPA : How can I create a table for each subclass but not for superclass?

git - Unity 协作与 GitHub

c# - 如何检测 Unity 中发生碰撞的位置?