V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
img5d
V2EX  ›  C#

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

  •  
  •   img5d · 2020-02-21 10:14:14 +08:00 · 8066 次点击
    这是一个创建于 1497 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2020-02-21 15:52:34 +08:00
    MaxTan
        1
    MaxTan  
       2020-02-21 10:28:05 +08:00   ❤️ 1
    可以去掉没毛病,当局部变量和类成员有重名时就需要加 this 来明确了,类似这样

    ```
    class Student
    {
    private int age;

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

    ```
    img5d
        2
    img5d  
    OP
       2020-02-21 15:52:34 +08:00
    @MaxTan 哦哦哦 这样啊 谢谢谢谢!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1155 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 23:02 · PVG 07:02 · LAX 16:02 · JFK 19:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.