我有一个Deck类,可以实例化你的标准52卡套牌。我正在制作Durak纸牌游戏,它允许你使用不同尺寸的套牌。所以我继承了Deck,使用了新的DurakDeck类。
我有以下DurakDeck构造函数(我也有一个默认构造函数,或多或少做类似的事情)。我遇到了一个问题,看起来当我实例化DurakDeck时,它也调用了Deck构造函数,因为我的DurakDeck对象最终包含许多卡,它被告知要在其构造函数中实例化,另外还有一个52-卡(来自甲板)。
父类构造函数是否自动调用?我总是认为只有在你指定: 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));
}
}
}
答案 0 :(得分:1)
自动调用基础构造函数。使用:Base()使您能够指定基础构造函数的输入。
查看更多信息Will the base class constructor be automatically called?
答案 1 :(得分:0)
如果您的基类有一个默认构造函数,它将始终被调用,除非您指定另一个要调用的基类。
答案 2 :(得分:0)
class ParentClass
{
public ParentClass(){
Console.WriteLine("parent created");
}
}
class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("child created");
}
}
ChildClass cc = new ChildClass(); 打印“父创建”,然后打印“子创建”。