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

2020-02-21 10:14:14 +08:00
 img5d
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");
}

}
}
}
8105 次点击
所在节点    C#
2 条回复
MaxTan
2020-02-21 10:28:05 +08:00
可以去掉没毛病,当局部变量和类成员有重名时就需要加 this 来明确了,类似这样

```
class Student
{
private int age;

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

```
img5d
2020-02-21 15:52:34 +08:00
@MaxTan 哦哦哦 这样啊 谢谢谢谢!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/646276

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX