当int超出我的else-if语句的界限时,我的setter不会返回0

Mur*_*xas -1 c# arrays constructor class object

我的构造函数应该返回只要比分是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);

         }
     }
 }
Run Code Online (Sandbox Code Playgroud)

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.");
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)

15e*_*153 5

你不是范围检查value,这是新值.你是范围检查Score- 旧的价值.这是你打算做的:

     set
     {
         if (value >= 0 && value <= 300)
         {
             this.score = value;
         }
         else
         {
             this.score = 0;
         }
     }
Run Code Online (Sandbox Code Playgroud)

我猜这只是心不在焉.

UPDATE

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

     set
     {
         this.score = (value >= 0 && value <= 300)
                          ? value
                          : 0;
     }
Run Code Online (Sandbox Code Playgroud)

...但是,如果这看起来像是对你的线路噪音,坚持你所拥有的!

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