在OOP中,关于使用“这个”的最佳实践是什么,里面一个类? [英] In OOP, what is the best practice in regards to using "this" inside a class?
问题描述
我一直想知道的东西;在某个类中,您可以使用this。[NAME]或简单的[NAME]来引用成员,这是首选?
/ p>
public class foo {
public int bars = 0;
private void incrementBars(){
bars ++;
}
}
和
public class foo {
public int bars = 0;
private void incrementBars(){
this.bars ++;
}
}
具有相同的效果。 p>
在我实例化类foo的多个实例的情况下,到目前为止,我做了类似的操作:
for(foo f:listOfFoos){
f.incrementBars();
}
似乎仍然有效。
$
如果是这样, http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html =nofollow> 此
变量遮蔽
。
class MyClass {
int i; // 1
public void myMethod(){
i = 10; // refer to 1
}
public void myMethod(int i){// 2
i = 10;引用2
this.i = 10 //引用1
}
}
b $ b
也有时 这
会让代码更具可读性,因为我们的英语思维方式
Something I've always wondered; in a class where you can reference a member by either using 'this.[NAME]' or simply [NAME], which is preferred?
For example in Java:
public class foo {
public int bars = 0;
private void incrementBars(){
bars++;
}
}
and
public class foo {
public int bars = 0;
private void incrementBars(){
this.bars++;
}
}
'seem' to have the same effect.
In cases where I instantiate multiple instances of class foo, I'd, so far, do something like:
for (foo f : listOfFoos){
f.incrementBars();
}
and it seems to still work.
Is it technically ambiguous, and if so is there a preferred way?
use this
in the case of variable shadowing
.
class MyClass{
int i;//1
public void myMethod(){
i = 10;//referring to 1
}
public void myMethod(int i){//2
i = 10;//referring to 2
this.i = 10 //refering to 1
}
}
also sometime this
will make code more readable due to our English mindset
这篇关于在OOP中,关于使用“这个”的最佳实践是什么,里面一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!