V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
img5d
V2EX  ›  C#

在跟着刘铁猛老师学习的过程里, This,不太明白 例如下面这段代码 注释的地方去掉 this. 不会报错 编译结果也一样 可是这么写是不是就不对了呢? *(不太会排版)

  •  
  •   img5d · Feb 21, 2020 · 8975 views
    This topic created in 2260 days ago, the information mentioned may be changed or developed.
    namespace PropertyExamples
    {
    class Program
    {
    static void Main(string[] args)
    {
    try
    {
    Student stu1 = new Student();
    stu1.SetAge(20);
    Student stu2 = new Student();
    stu2.SetAge(20);
    Student stu3 = new Student();
    stu3.SetAge(200);

    int avgAge = (stu1.GetAge() + stu2.GetAge() + stu3.GetAge() / 3);
    Console.WriteLine(avgAge);
    }
    catch (Exception wx)
    {
    Console.WriteLine(wx.Message);
    }




    }
    }

    class Student
    {
    private int age;

    public int GetAge()
    {
    return this.age; // 请看这里
    }

    public void SetAge(int value)
    {
    if (value>=0 && value <= 120)
    {
    this.age = value; // 请看这里
    }
    else
    {
    throw new Exception("Age value has error");
    }

    }
    }
    }
    2 replies    2020-02-21 15:52:34 +08:00
    MaxTan
        1
    MaxTan  
       Feb 21, 2020   ❤️ 1
    可以去掉没毛病,当局部变量和类成员有重名时就需要加 this 来明确了,类似这样

    ```
    class Student
    {
    private int age;

    public int GetAge()
    {
    int age = 20;
    return this.age; //不加 this 就是 return 局部变量 age
    }
    }

    ```
    img5d
        2
    img5d  
    OP
       Feb 21, 2020
    @MaxTan 哦哦哦 这样啊 谢谢谢谢!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2766 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 11:02 · PVG 19:02 · LAX 04:02 · JFK 07:02
    ♥ Do have faith in what you're doing.