亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法更改屬性的值

無法更改屬性的值

C#
米琪卡哇伊 2021-06-03 21:14:20
我目前正在改進我在 CR 上發布的程序,但遇到了問題。我有一個被調用的屬性,Total但是當我嘗試將它設置為值 (0) 時,它保持不變。這是物業:public class Player{    private int total;    public int Total    {        get        {            total = 0;            foreach (int card in hand)            {                total += card;            }            return total;        }        set { this.total = value; }    }}這是我嘗試改變它的方式:public class Game{    private void CompareHands()    {        //This is just for testing        Console.WriteLine($"player total: {player1.Total}, is bust: {player1.Bust}");        Console.WriteLine($"house total: {house.Total}, is bust: {house.Bust}");        if (player1.Bust)            player1.Total = 0;        if (house.Bust)            house.Total = 0;        //this too        Console.WriteLine($"player total: {player1.Total}, is bust: {player1.Bust}");        Console.WriteLine($"house total: {house.Total}, is bust: {house.Bust}");...}如果需要,還有 Bust 屬性:    private readonly int blackjack = 21;    public bool Bust    {        get { return Bust = Total > blackjack; }        private set { }    }
查看完整描述

2 回答

?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

如果我是你,我會將 Total 計算和 Bust 分開一點:


public class Player

{

    public bool Bust { get; set; }


    public int GetTotal()

    {

        if (Bust)

        {

            return 0;

        }


        var total = 0;

        foreach (int card in hand)

        {

            total += card;

        }

        return total;

    }

}

需要注意的幾點:

  • 計算是通過一種方法而不是屬性完成的 - 我認為這是一種更簡潔的方法,因為屬性應該非常簡單并且其中沒有任何邏輯

  • 在 GetTotal 計算中包含 Bust 并在 Bust 設置為 true 時返回 0

  • 始終計算總價值,除非您有充分的理由擁有它的緩存版本

希望這可以幫助。


查看完整回答
反對 回復 2021-06-05
?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

實際上,每次調用屬性的 getter 時,您都會重新計算總數。


一個解決辦法是讓現場total的Nullable<int>所以如果是null,你做你正在做的其實不然返回的內容在現場設置的邏輯total。


public class Player

{

    private int? total; // <- Nullable<int> here

    public int Total

    {

        get

        {

            if(total.HasValue) // <- If value is set return that value.

            {

                return total.Value;

            }


            total = 0;

            foreach (int card in hand)

            {

                total += card;

            }


            return total.Value;

        }

        set { this.total = value; }

    }

}


查看完整回答
反對 回復 2021-06-05
  • 2 回答
  • 0 關注
  • 201 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號