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

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

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

   首先給Card類添加額外字段,允許使用“王牌”花色,使A有更高的級(jí)別。把這些字段指定為靜態(tài),因?yàn)樵O(shè)置它們后,它們就可以應(yīng)用到所有Card對(duì)象上:

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

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

/// <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è)構(gòu)造函數(shù)都使用:this()語(yǔ)法來(lái)定義,這樣,無(wú)論如何,默認(rèn)構(gòu)造函數(shù)總會(huì)在非默認(rèn)的構(gòu)造函數(shù)之前被調(diào)用,以初始化撲克牌。

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

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