【问题标题】:"this" operator not working“this”运算符不工作
【发布时间】:2016-04-04 19:32:09
【问题描述】:

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

【问题讨论】:

  • this._ID = Id; 应该在if {} 之外,否则它永远不会被写入。将鼠标悬停在带下划线的符号上/查看左边距,VS 会告诉你它在抱怨什么。
  • 好的,但是为什么在我的 Visual Studio 中它是浅蓝色的?
  • @ZvezdaBre 看看我的回答

标签: c# get set this


【解决方案1】:

您仅在 (Id

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

你的this 调用是浅蓝色的,因为VS 告诉你你不需要在这里使用它。您没有同名的局部变量。阅读更多关于thishere

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

【讨论】:

    【解决方案2】:

    我建议将 both getset 方法重新设计为单个 property;您无需在 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);
    }
    

    【讨论】:

      【解决方案3】:

      试试这个

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

      【讨论】:

      • 好的,谢谢。我忘记了。
      猜你喜欢
      • 2015-01-12
      • 2015-01-26
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2013-07-12
      • 2012-08-11
      • 1970-01-01
      相关资源
      最近更新 更多