C# 何时使用“This"关键词 [英] C# When To Use "This" Keyword
问题描述
可能的重复:
你什么时候使用这个"?关键字?
你好,我知道 This
关键字用于引用类的实例,但是,假设我有一个名为 Life
的类,它定义了两个字段,即 person (他们的名字)和他们的伴侣(他们的名字):
Hello,
I understand that the This
keyword is used to refer to an instance of the class, however, suppose I have a class called Life
, which defines two fields, the person (their name) and their partner(their name):
class Life
{
//Fields
private string _person;
private string _partner;
//Properties
public string Person
{
get { return _person; }
set { _person = value; }
}
public string Partner
{
get { return _partner; }
set { _partner = value; }
}
//Constructor 1
public Life()
{
_person = "Dave";
_partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
//Constructor 2
public Life()
{
this._person = "Dave";
this._partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
构造函数1和构造函数2有区别吗!?还是使用This"关键字只是更好的编码习惯?
Is there a difference between constructor 1 and constructor 2!? Or is it just better coding practice to use the "This" keyword?
问候
推荐答案
构造函数相同.我更喜欢第二个的原因是它允许您从私有变量名称中删除下划线并保留上下文(提高可理解性).我习惯于在引用实例变量和属性时始终使用 this
.
The constructors are the same. The reason I would prefer the second is that it will allow you to remove the underscores from your private variable names and retain the context (improving understandability). I make it a practice to always use this
when referring to instance variables and properties.
在搬到不同标准的不同公司后,我不再以这种方式使用 this
关键字.我已经习惯了,现在在提到实例成员时很少使用它.我仍然建议使用属性(显然).
I no longer use the this
keyword in this way after moving to a different company with different standards. I've gotten used to it and now rarely use it at all when referring to instance members. I do still recommend using properties (obviously).
我的课程版本:
class Life
{
//Fields
private string person;
private string partner;
//Properties
public string Person
{
get { return this.person; }
set { this.person = value; }
}
public string Partner
{
get { return this.partner; }
set { this.partner = value; }
}
public Life()
{
this.person = "Dave";
this.partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
或者,甚至更好,但不清楚 this
与字段的使用.
or, even better, but not as clear about the use of this
with fields.
class Life
{
//Properties
public string Person { get; set; }
public string Partner { get; set; }
public Life()
{
this.Person = "Dave";
this.Partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
这篇关于C# 何时使用“This"关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!