C# 给 CardLib 添加 Cards 集合
这个新类Cards是Card对象的一个定制集合。在C:\BegirniingCSharp7\Chapter11目录中创建一个新的类库CMICardLib。然后删除自动生成的 Classl.cs 文件,再通过 Project 丨 Add Existing Item 命令选择 C:\BeginningCSharp7\Chapter10\Chl10CardLib目录中的Card.cs、Deck.cs、Suit.cs和Rank.cs文件,把它们添加到项目中。
如果要自己创建这个项目,就应添加一个新类Cards,并修改Cards.cs中的代码,如下所示:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System,Threading.Tasks;
namespace ChllCardLib
{
public class Cards : CollectionBase
{
public void Add(Card newCard} => List.Add(newCard);
public void Remove(Card oldCard) => List.Remove(oldCard);
public Card this[int cardlndex]
{
get { return (Card)List[cardlndex]; }
set { List[cardlndex] = value; }
}
/// <summary>
/// Utility method for copying card instances into another Cards
/// instanco—used in Deck.Shuffle(). This implementation assumes that
/// source and target collections are the same size.
/// </summary>
public void CopyTo(Cards targetCards)
{
for (int index = 0; index < this.Count; index++)
{
targetCards[index] = this[index];
}
}
/// <sumzoary>
/// Check to see if the Cards collection contains a particular card.
/// This calls the Contains() method of the ArrayList for the collection,
/// which you access through the InnerList property.
/// </suromary>
public bool Contains(Card card) => InnerList.Contains(card);
}
}
然后需要修改Deck.cs,以利用这个新集合(而不是数组):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChllCardLib
{
public class Deck
{
private Cards cards = new Cards();
public Deck()
{
// Line of code removed here
for (int suitVal = 0; suitVal < 4; suitVal++)
{
for (int rankVal = 1; rankVal < 14; rankVal++)
{
cards.Add(new Card((Suit)suitVal, (Rank)rankVal));
}
}
}
public Card GetCard(int cardNum)
{
if (cardNum >= 0 && cardNum <= 51)
return cards[cardNum];
else
throw (new System.ArgumentOutOfRangeException{"cardNum", cardNum, "Value must be between 0 and 51."));
}
public void Shuffle()
{
Cards newDeck » new Cards();
bool[] assigned = new bool[52];
Random sourceGen = new Random ();
for (int i = 0; i < 52; i++)
{
int sourceCard = 0;
bool foundCard = false;
while {foundCard == false)
{
sourceCard = sourceGen.Next(52);
if (assigned[sourceCard] == false)
foundCard = true;
}
assigned[sourceCard] = true;
newDeclc .Add(cards [sourceCard]};
}
newDeck.CopyTo < cards);
}
}
}
在此不需要做很多修改。其中大多数修改都涉及改变洗牌逻辑,才能把cards中随机的一张牌添加到新Cards集合newDeck的开头,而不是把cards集合中顺序位置的一张牌添加newDeck集合的随机位置上。
ChlOCardLib解决方案的客户控制台应用程序ChlOCardClient可使用这个新库得到与以前相同的结果,因为Deck的方法签名没有改变。这个类库的客户程序现在可以使用Caixls集合类,而不是依赖于CanI对象数组,例如,在扑克牌游戏应用程序中定义一手牌。
点击加载更多评论>>