为了账号安全,请及时绑定邮箱和手机立即绑定

无法更改属性的值

无法更改属性的值

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 关注
  • 152 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信