我有以下代码,显然有一些重复。我确信这可以使用委托或动作删除,但不能完全掌握它。
谁有任何想法?public void DealStartingCards()
{
for (int i = 0; i < 3; i++)
{
foreach (var player in Players)
{
if (player.Hand.FaceDownCards.Count < 3)
{
if (Deck.Count > 0)
player.Hand.FaceDownCards.Add(Deck.TakeTopCard());
}
}
}
for (int i = 0; i < 3; i++)
{
foreach (var player in Players)
{
if (player.Hand.FaceUpCards.Count < 3)
{
if (Deck.Count > 0)
player.Hand.FaceUpCards.Add(Deck.TakeTopCard());
}
}
}
for (int i = 0; i < 3; i++)
{
foreach (var player in Players)
{
if (player.Hand.InHandCards.Count < 3)
{
if (Deck.Count > 0)
player.Hand.InHandCards.Add(Deck.TakeTopCard());
}
}
}
}
InHandCards,FaceUpCards和FaceDownCards都是List<Card>
答案 0 :(得分:4)
采用奥斯卡的解决方案并稍作改动:
private void DealCards(Func<Hand, List<Card>> handProjection)
{
for (int i = 0; i < 3; i++)
{
foreach (var player in Players)
{
List<Card> cards = handProjection(player.Hand);
if (cards.Count < 3)
{
if (Deck.Count > 0)
{
cards.Add(Deck.TakeTopCard());
}
}
}
}
}
public void DealStartingCards()
{
DealCards(hand => hand.FaceDownCards);
DealCards(hand => hand.FaceUpCards);
DealCards(hand => hand.InHandCards);
}
(假设player.Hand
的类型为Hand
- 当然也会相应调整。)