【问题标题】:Base class constructor running without being specified to未指定运行的基类构造函数
【发布时间】:2015-05-31 22:45:14
【问题描述】:

我有一个 Deck 类,可以实例化您的标准 52 张牌。我正在制作一个 Durak 纸牌游戏,它允许您使用不同大小的套牌。所以我继承了 Deck,带有一个新的 DurakDeck 类。

我有以下 DurakDeck 构造函数(我也有一个默认构造函数,它或多或少做了类似的事情)。我遇到了一个问题,看起来当我实例化一个 DurakDeck 时,它也在调用 Deck 构造函数,因为我的 DurakDeck 对象最终包含了它被告知在它的构造函数中实例化的许多卡片,加上一个额外的 52-卡片(来自 Deck)。

父类构造函数会自动调用吗?我一直认为它只有在您指定了 : base() 时才会调用...?

不确定我哪里出错了......

public DurakDeck(byte deckSize)
        {
            const Rank SMALL_DECK_START = Rank.Ten;
            const Rank NORMAL_DECK_START = Rank.Six;
            const Rank LARGE_DECK_START = Rank.Deuce;

            this.deckSize = (deckSize - 1);
            Rank startingValue = Rank.Six;

            // Check what deckSize is equal to, and start building the deck at the required card rank.
            if (deckSize == SMALL_SIZE) { startingValue = SMALL_DECK_START; }
            else if (deckSize == NORMAL_SIZE) { startingValue = NORMAL_DECK_START; }
            else if (deckSize == LARGE_SIZE) { startingValue = LARGE_DECK_START; }
            else { startingValue = NORMAL_DECK_START; }

            // Ace is 1 in enum, and Durak deck can initialize at different sizes,
            //  so we add the aces of each 4 suits first.
            for (int suitVal = 0; suitVal < 4; suitVal++)
            {
                cards.Add(new Card((Suit)suitVal, Rank.Ace));
            }

            // Loop through every suit
            for (int suitVal = 0; suitVal < 4; suitVal++)
            {
                // Loop through every rank starting at the starting value determined from the if logic up above.
                for (Rank rankVal = startingValue; rankVal <= Rank.King; rankVal++)
                {
                    // Add card to deck
                    cards.Add(new Card((Suit)suitVal, rankVal));
                } 
            }
        }

【问题讨论】:

    标签: c# inheritance constructor


    【解决方案1】:

    自动调用基本构造函数。使用 :Base () 可以指定基本构造函数的输入。

    更多信息请参见Will the base class constructor be automatically called?

    【讨论】:

    • 那么在 Deck 类中添加一个空的构造函数对我来说是不是很理想?
    • 我不确定你如何设想 Deck 负责什么,但你可以为 Deck 创建一个构造函数 Deck(int deckSize) 并使用 DurakDeck(byte size):base(size-1)
    【解决方案2】:

    如果您的基类有一个默认构造函数,它将始终被调用,除非您指定另一个要调用的构造函数。

    【讨论】:

      【解决方案3】:
          class ParentClass
          {
              public ParentClass(){
                  Console.WriteLine("parent created");
              }
          }
          class ChildClass : ParentClass
          {
              public ChildClass()
              {
                  Console.WriteLine("child created");
              }
          }
      

      ChildClass cc = new ChildClass(); 打印“父创建”,然后打印“子创建”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-26
        • 2016-07-19
        相关资源
        最近更新 更多