问题描述
引用类变量时,为什么人们用 this
加上它?我不是在说这个
用于消除方法参数的歧义,而是当它似乎不必要时。
示例:
public class Person {
private String name;
public String toString(){
return this.name;
}
}
在 toString
,为什么不只是引用 name
as name
?
$ b b
返回名称;
this.name
/ p>
a相同的原因:
When referencing class variables, why do people prepend it with this
? I'm not talking about the case when this
is used to disambiguate from method parameters, but rather when it seems unnecessary.
Example:
public class Person {
private String name;
public String toString() {
return this.name;
}
}
In toString
, why not just reference name
as name
?
return name;
What does this.name
buy?
Here's a stackoverflow question whose code has this
pre-pending.
Same reason why some people like to prepend private data members with "m_" or name interfaces "IFoo". They believe it increases readability and clarity. Whether or not you agree with conventions like these is a matter of taste.
这篇关于在Java中,为什么人们用`this`前缀字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!