简体   繁体   中英

Using the get;set statements to exclude values greater than or less than in C#

I've been following a tutorial online that looks at students, their subject and grade.and I've been introduced to the get and set statements. How would I ammend them the class to include "NA" for a grade that is =<0 or >5.3?

I still want to maintain a grade > 3.5 is an honours

class Student
{
    public string Name;
    public string Subject;
    public double Grade;

    public Student(string aName, string aSubject, double aGrade)
    {
        Name = aName;
        Subject = aSubject;
        Grade = aGrade;

    }
    public double grade
    {
        get { return Grade; }
        set {
            if (value > 5.3 || value <= 0)
            { grade = string "na";
            }
            else
            { grade = value;
            }


            public bool HasHonours()
            { if (Grade >= 3.5)
                {
                    return true;
                }
                return false;
            }
        }
    }
}

It was just needing the NaN operator:

namespace student
{
   class Student
   {
      public string Name;
      public string Subject;
      public double Grade;

      public Student(string aName, string aSubject, double Grade)
      {
         Name = aName;
         Subject = aSubject;
         grade=Grade;
      }

      private double grade
      {
         get { return Grade; }
         set
         {
            if (value > 5.3 || value <= 0)
            {
               Grade = Double.NaN;
            }
            else
            {
               Grade = value;
            }

         }
      }

      public bool HasHonours()
      { 
         if (grade >= 3.5)
         {
            return true;
         }
         else
         {
             return false;
         } 
      }
   }
} 

Try this.

class Student
{
   public string Name { get; set; };
   public string Subject { get; set; };

   public double Grade 
   {
      get
      {
         return Grade;
      }

     set
     {
        // value is less than or equal to '0' or greater than '5.3' so return 'N/A'
        if(!(value <= 0 || value > 5.3))
           Grade = value;
     }
   };

   public Student(string name, string subject, double grade)
   {
      this.Name = name;
      this.Subject = subject;
      this.Grade = grade;
   }

   public bool HasHonours()
   { 
      if (grade > 3.5)
      {
         return true;
      }
      else
      {
         return false; // Because - Grade is Less than or equal to 3.5
      } 
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM