C#何时使用"本"关键词 [英] C# When To Use "This" Keyword
问题描述
可能重复:结果
当你使用“这”的关键字?
您好,
据我所知,这
关键字用来指类的实例,但是,假设我有一类称为人寿
,它定义了两个字段,这个人(的他们的名字的)和他们的合作伙伴(的他们的名字的):
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的构造函数之间的差异!?
还是只是更好的编码的做法是使用了这个关键字?
Is there a difference between constructor 1 and constructor 2!? Or is it just better coding practice to use the "This" keyword?
问候
推荐答案
的构造是相同的。 <罢>我想preFER第二个是,它可以让你从你的私有变量名称中删除下划线并保留上下文(可理解性改善)的原因。我让实践始终使用这个
引用实例变量和属性时。击>
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.
我不再使用这个
关键字以这种方式移动到不同的公司不同的标准之后。我已经习惯了它,现在参照实例成员时,很少使用它。我还是建议使用属性(显然)。
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");
}
}
,或者甚至更好,但不是使用清晰这个
与领域。
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#何时使用&QUOT;本&QUOT;关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!