【问题标题】:My setter won't return 0 when an int is out of bounds of my else-if statement当 int 超出 else-if 语句的范围时,我的 setter 不会返回 0
【发布时间】:2018-03-28 06:13:37
【问题描述】:

只要分数在 0 到 300 之间,我的构造函数就应该返回给定的分数。如果分数超出此边界,则应返回 0 值。但是,它返回的是我给我的班级的值,而不是我设置的值。 主程序

namespace ClassScores
{
     class Program
     {
         static void Main(string[] args)
         {
             int runningTotal = 0;
             double average = 0;
             .....
             Bowler Jesus = new Bowler("Jesus", 450);
             bowlers[3] = Jesus;
             for (int i=0; i <= 4; i++)
             {
             runningTotal=runningTotal + bowlers[i].Score;
             }
             average = Convert.ToDouble(runningTotal/5);
             Console.WriteLine("The average bowler score is " + average);

         }
     }
 }

namespace ClassScores
{
     class Bowler

     {
         private string name;
         private int score;
         public string Name
         {
          .....
         }
         public int Score
         {
             get
             {
                 return this.score;
             }
             set
             {
                 if (Score>=0 && Score <=300)
                 {
                     this.score = value;
                 }
                 else
                 {
                     this.score = 0;
                 }
             }
         }

         public Bowler (string name, int score)
         {
             this.Name = name;
             this.Score = score;
         }
         public string ToString()
         {
             return (Name + " has a score of " + Convert.ToString(Score) + "  points.");
         }
     }
 }

【问题讨论】:

    标签: c# arrays class object constructor


    【解决方案1】:

    您没有对value 进行范围检查,这是新值。您正在检查Score 的范围—— old 值。这是你打算做的:

         set
         {
             if (value >= 0 && value <= 300)
             {
                 this.score = value;
             }
             else
             {
                 this.score = 0;
             }
         }
    

    我猜这只是心不在焉。

    更新

    你可以不那么冗长地做同样的事情:

         set
         {
             this.score = (value >= 0 && value <= 300)
                              ? value
                              : 0;
         }
    

    ...但是,如果这对您来说像是线路噪音,请坚持使用您所拥有的!

    我建议的另一件事是将score 重命名为_score。这是私有字段的 C# 约定,它可以防止您在真正想设置 Score 时意外设置 score

    【讨论】:

    • 在这里使用?: 操作符会很好
    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2021-08-31
    • 2013-09-09
    • 1970-01-01
    • 2019-03-18
    • 2023-02-21
    • 2020-01-11
    相关资源
    最近更新 更多