位置:首頁 > 軟件操作教程 > 編程開發(fā) > C# > 問題詳情

C# 給CardUb添加運(yùn)算符重載

提問人:劉團(tuán)圓發(fā)布時間:2020-12-07

   首先給Card類添加額外字段,允許使用“王牌”花色,使A有更高的級別。把這些字段指定為靜態(tài),因?yàn)樵O(shè)置它們后,它們就可以應(yīng)用到所有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;

    這些規(guī)則應(yīng)用于應(yīng)用程序中每個Deck的所有Card對象上?因此,兩個Deck中的Card不可能遵守不同規(guī)則。這適用于這個類庫,但是確實(shí)可以做出這樣的假設(shè):如果一個應(yīng)用程序要使用不同的規(guī)則,可以自行維護(hù)這些規(guī)則;例如,在切換牌時,設(shè)置Card的靜態(tài)成員。

    完成后,就要給Deck類再添加幾個構(gòu)造函數(shù),以便用不同的特性來初始化撲克牌:

/// <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;

}

每個構(gòu)造函數(shù)都使用:this()語法來定義,這樣,無論如何,默認(rèn)構(gòu)造函數(shù)總會在非默認(rèn)的構(gòu)造函數(shù)之前被調(diào)用,以初始化撲克牌。

繼續(xù)查找其他問題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部