基础 class 构造函数 运行 未被指定为

Base class constructor running without being specified to

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

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

父class构造函数是否自动调用?我一直认为它只有在您指定了 : 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));
                } 
            }
        }

如果您的基础 class 有默认构造函数,它将始终被调用,除非您指定要调用的替代构造函数。

自动调用基础构造函数。使用 :Base () 使您能够指定基本构造函数的输入。

查看更多信息Will the base class constructor be automatically called?

    class ParentClass
    {
        public ParentClass(){
            Console.WriteLine("parent created");
        }
    }
    class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine("child created");
        }
    }

ChildClass cc = new ChildClass(); 打印 "parent created",然后打印 "child created"。