C# 给CardUb添加运算符重载
首先给Card类添加额外字段,允许使用“王牌”花色,使A有更高的级别。把这些字段指定为静态,因为设置它们后,它们就可以应用到所有Card对象上:
public class Card
{
/// <suxnmary>
/// Flag for trump usage. If true, trumps are valued higher
/// than cards of other suits.
/// </summary>
public static bool useTrumps = false;
/// <summary>
/// Trump suit to use if useTrumps is true.
/// </summary>
public static Suit trump = Suit.Club;
/// <sumraary>
/// Flag that determines whether aces are higher than kings or lower
/// than deuces,
/// </sunuuary>
public static bool isAceHigh = true;
这些规则应用于应用程序中每个Deck的所有Card对象上„因此,两个Deck中的Card不可能遵守不同规则。这适用于这个类库,但是确实可以做出这样的假设:如果一个应用程序要使用不同的规则,可以自行维护这些规则;例如,在切换牌时,设置Card的静态成员。
完成后,就要给Deck类再添加几个构造函数,以便用不同的特性来初始化扑克牌:
/// <summary>
/// Nondefault constructor. Allows aces to be set high.
/// </summary>
public Deck{bool isAceHigh) : this()
{
Card.isAceHigh = isAceHigh;
}
/// <summary>
/// Nondefault constructor. Allows a trump suit to be used.
/// </sununary>
public Deck(bool useTrumps, Suit trump) : this()
{
Card.useTrumps = useTrumps;
Card.trump = trump;
}
/// <summary>
/// Nondefault constructor. Allows aces to be set high and a trump suit
/// to be used.
/// </suirunary>
public Deck(bool isAceHigh, bool useTrumps, Suit trump) : this()
{
Card.isAceHigh = isAceHigh;
Card.useTrumps = useTrumps;
Card.trump = trump;
}
每个构造函数都使用:this()语法来定义,这样,无论如何,默认构造函数总会在非默认的构造函数之前被调用,以初始化扑克牌。
点击加载更多评论>>