C#何时使用“此”关键字
可能重复:
你什么时候使用“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"); } }
构造函数1和构造函数2之间是否存在差异!? 或者使用“This”关键字是否只是更好的编码习惯?
问候
构造函数是相同的。 我更喜欢第二个的原因是它允许你从私有变量名中删除下划线并保留上下文(提高可理解性)。 我指的是在引用实例变量和属性时总是使用 this
。
在转移到具有不同标准的其他公司后,我不再以这种方式使用this
关键字。 我已经习惯了它,现在在引用实例成员时很少使用它。 我仍然建议使用属性(显然)。
我的class级版本:
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
与田地的使用。
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"); } }
“this”也在.Net 3.5中使用扩展方法:
public static class MyExtensions { public static string Extend(this string text) { return text + " world"; } }
会扩展字符串类
var text = "Hello"; text.Extend();
回答你的问题:不,你的两个构造函数没有区别。 Imo,“this”使代码混乱,只应在必要时使用,例如当参数和字段变量具有相同名称时。
还有一种情况是类显式实现了接口。 如果需要从类中调用接口方法,则必须将其转换为接口:
class Impl : IFace { public void DoStuff() { ((IFace)this).SomeMethod(); } void IFace.SomeMethod() { } }
这两个陈述没有区别……
//These are exactly the same. this._person //and _person
在_person的情况下隐含了对“this”的引用。 我不会说它必然是“更好”的编码实践,我会说它只是偏好。
已经讨论过了
你什么时候使用“this”关键字?
由于您使用下划线,因此名称之间不存在冲突; 所以“ this.
”是多余的,可以省略。 IL将不受影响。
只要字段和变量/ parareter之间没有歧义,只有一种情况是this
关键字(在当前实例的意义上下文 – 不是ctor-chaining)是严格必要的 – 调用一个扩展方法单独定义:
this.SomeExtensionMethod(); // works SomeExtensionMethod(); // fails
在第二个构造函数中,两个构造函数都做同样的事情, this
是多余的
您可以使用它来区分名为X的局部变量和同名的类级别字段/属性。
您不应该使用私有变量_person和_parter。 这是你的吸气者和制定者的目的。
就构造而言,它们之间没有真正的区别。 话虽这么说,我总是喜欢使用This关键字,因为它有助于提高可读性。