"这"运营商无法运作

时间:2016-04-04 11:10:29

标签: c# get set this

每次我使用this._Something时,我的this.都是浅蓝色,并且有绿色下划线。在F5之后我无法获得101的价值。相反,我得到价值0.任何帮助?

class Student
{
    private int _ID;

    public void SetID(int Id)
    {
        if (Id <= 0)
        {
            throw new Exception("It is not a Valid ID");
            this._ID = Id;
        }
    }

    public int GetID()
    {
        return this._ID;
    }
}

class Program
{
    public static void Main()
    {
        Student C1 = new Student();
        C1.SetID(101);
        Console.WriteLine("Student ID = {0}", C1.GetID());
    }
}

3 个答案:

答案 0 :(得分:3)

仅在(Id <= 0)时才分配_ID,将代码更改为:

public void SetID(int Id)
{
    if (Id <= 0)
    {
        throw new Exception("It is not a Valid ID");
    }
    _ID = Id;
}

您的this电话是浅蓝色的,因为VS告诉您,您不需要在此处使用它。你没有同名的本地变量。详细了解this here

顺便说一句,您应该阅读有关支持字段的属性,例如here

答案 1 :(得分:3)

我建议将 getset方法重新设计为单个属性;您无需在 C#中模仿 Java

 class Student {
   private int _ID; 

   public int ID {
     get {
       return _ID;
     }
     set {
       // input validation:
       // be exact, do not throw Exception but ArgumentOutOfRangeException:
       // it's argument that's wrong and it's wrong because it's out of range 
       if (value <= 0) 
         throw new ArgumentOutOfRangeException("value", "Id must be positive");

       _ID = value;
     }
   }
 }

...

public static void Main()
{
    Student C1 = new Student();
    C1.ID = 101;
    Console.WriteLine("Student ID = {0}", C1.ID);
}

答案 2 :(得分:1)

试试这个

class Student
{
    private int _ID;

    public int ID
    {
        get{ return _ID;}

        set {
            if (value <= 0)
                throw new Exception("It is not a Valid ID");
            _ID = value;
           }

    }


}

class Program
{
    public static void Main()
    {
        Student C1 = new Student();
        C1.ID=101;
        Console.WriteLine("Student ID = {0}", C1.ID);
    }
}