Goo*_*ber 25 c# constructor this
可能重复:
您何时使用"this"关键字?
您好,我知道该This
关键字用于引用该类的实例,但是,假设我有一个名为的类Life
,它定义了两个字段,person(他们的名字)和他们的伙伴(他们的名字):
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");
}
}
Run Code Online (Sandbox Code Playgroud)
构造函数1和构造函数2之间是否存在差异!?或者使用"This"关键字更好的编码实践?
问候
tva*_*son 23
构造函数是相同的. 我更喜欢第二个的原因是它允许你从私有变量名中删除下划线并保留上下文(提高可理解性).我this
指的是在引用实例变量和属性时总是使用它.
this
在转移到具有不同标准的不同公司后,我不再以这种方式使用该关键字.我已经习惯了它,现在在引用实例成员时很少使用它.我仍然建议使用属性(显然).
我的班级版本:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
或者,甚至更好,但不清楚使用this
字段.
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");
}
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*old 13
"this"也在.Net 3.5中使用扩展方法:
public static class MyExtensions
{
public static string Extend(this string text)
{
return text + " world";
}
}
Run Code Online (Sandbox Code Playgroud)
会扩展字符串类
var text = "Hello";
text.Extend();
Run Code Online (Sandbox Code Playgroud)
回答你的问题:不,你的两个构造函数没有区别.Imo,"this"使代码混乱,只应在必要时使用,例如,当参数和字段变量具有相同的名称时.
还有一种情况是类显式实现了接口.如果需要从类中调用接口方法,则必须将其转换为接口:
class Impl : IFace
{
public void DoStuff()
{
((IFace)this).SomeMethod();
}
void IFace.SomeMethod()
{
}
}
Run Code Online (Sandbox Code Playgroud)
这两个陈述没有区别......
//These are exactly the same.
this._person
//and
_person
Run Code Online (Sandbox Code Playgroud)
在_person的情况下隐含了对"this"的引用.我不会说它必然是"更好"的编码实践,我会说它只是偏好.