如何在派生构造函数

时间:2016-06-06 14:13:29

标签: c#

所以我得到了这个基类

abstract class Item
{
    private int x, y, ataque, defesa, saude, raridade;
    private char appearance;
    private bool pickedUp;
    private readonly Random rng = new Random();

    public Item(Map argMap, int argAtaque, int argDefesa, int argSaude, int argRaridade, char argAppearance)
    {
        bool empty = false;
        while (!empty)
        {
            x = rng.Next(1, argMap.ReLengthX() - 1);
            y = rng.Next(1, argMap.ReLengthY() - 1);
            if (!argMap.CheckTile(y, x)) empty = true;
        }
        pickedUp = false;
        ataque = argAtaque;
        defesa = argDefesa;
        saude = argSaude;
        raridade = argRaridade;
        appearance = argAppearance;
    }
}

我得到了这个派生类

class Armadura : Item
{
    public Armadura(Map argMap, int ataque, int defesa, int saude, int raridade, char appearance) : base(argMap, ataque, defesa, saude, raridade, appearance)
    {
        ataque = -1;
        defesa = 2;
        saude = 0;
        raridade = ReRNG().Next(Convert.ToInt32(Math.Round(argMap.ReLengthY() * 0.02)), Convert.ToInt32(Math.Round(argMap.ReLengthY() * 0.04)));
        appearance = ' ';
    }
}

所以我的问题是,如何设置值:base,使用我在派生构造函数上设置的值(例如,使用ataquewwww设置基础argAtaque,因此,argAtaque等于&#39 -1&#39)? 我尝试了几种方法,但我没有以任何方式使用它。 我提前谢谢你了!

2 个答案:

答案 0 :(得分:0)

: base()语法适用于常量和参数,但不适用于带有副作用的更复杂表达式(如您所见)。

您将需要基类的初始化方法。

abstract class Item
{
    ...

    // If you use this constructor, call Setup() afterwards.
    public Item() {}

    // Constructor including a call to Setup()
    public Item(Map argMap, int argAtaque, int argDefesa, int argSaude, int argRaridade, char argAppearance)
    {
        Setup(argMap, argAtaque, argDefesa, argSaude, argRaridade, argAppearance);
    }

    // Sets private variables for this Item
    protected void Setup(Map argMap, int argAtaque, int argDefesa, int argSaude, int argRaridade, char argAppearance)
    {
        bool empty = false;
        while (!empty)
        {
            x = rng.Next(1, argMap.ReLengthX() - 1);
            y = rng.Next(1, argMap.ReLengthY() - 1);
            if (!argMap.CheckTile(y, x)) empty = true;
        }
        pickedUp = false;
        ataque = argAtaque;
        defesa = argDefesa;
        saude = argSaude;
        raridade = argRaridade;
        appearance = argAppearance;
     }
}

现在,您可以使用计算值设置基类:

class Armadura : Item
{
    public Armadura(Map argMap) 
    {
        int ataque = -1;
        int defesa = 2;
        int saude = 0;
        int raridade = ReRNG().Next(Convert.ToInt32(Math.Round(argMap.ReLengthY() * 0.02)), Convert.ToInt32(Math.Round(argMap.ReLengthY() * 0.04)));
        char appearance = ' ';

        Setup(argMap, ataque, defesa, saude, raridade, appearance);
    }

答案 1 :(得分:0)

您只需在子构造函数中设置ataque,因为它将覆盖在基类中设置ataque的内容。首先调用基础构造函数,然后调用子构造函数。

为此,您需要在基类中保护您的私有变量。这将使它们成为子类中的私有。