“this”运算符不起作用。

4
每次我使用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());
    }
}

1
this._ID = Id; 应该放在 if {} 外面,否则它将永远不会被写入。将鼠标悬停在下划线符号上/查看左侧边缘,VS 将告诉您它的问题所在。 - Alex K.
好的,但为什么在我的Visual Studio中它是浅蓝色的? - Zvezda Bre
@ZvezdaBre 请看我的回答。 - Kamil Budziewski
3个回答

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的更多信息这里 顺便说一下,你应该了解带有后备字段的属性,例如这里

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);
}

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);
    }
}

是的,谢谢。我忘了它。 - MNF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接