无法更改属性的值

我目前正在改进我在 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 { }

    }


米琪卡哇伊
浏览 156回答 2
2回答

回首忆惘然

如果我是你,我会将 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始终计算总价值,除非您有充分的理由拥有它的缓存版本希望这可以帮助。

aluckdog

实际上,每次调用属性的 getter 时,您都会重新计算总数。一个解决办法是让现场total的Nullable<int>所以如果是null,你做你正在做的其实不然返回的内容在现场设置的逻辑total。public class Player{&nbsp; &nbsp; private int? total; // <- Nullable<int> here&nbsp; &nbsp; public int Total&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(total.HasValue) // <- If value is set return that value.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return total.Value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; total = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (int card in hand)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; total += card;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return total.Value;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; set { this.total = value; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP