我很好奇其他人是如何使用这个关键字的。我倾向于在构造函数中使用它,但我也可能在整个类的其他方法中使用它。一些例子:

在构造函数中:

public Light(Vector v)
{
    this.dir = new Vector(v);
}

在其他地方

public void SomeMethod()
{
    Vector vec = new Vector();
    double d = (vec * vec) - (this.radius * this.radius);
}

当前回答

只要StyleCop告诉我,我就使用它。必须遵守StyleCop。噢,是的。

其他回答

我使用它的时候,在一个函数中,接受了对同一类型对象的引用,我想完全清楚我引用的是哪个对象,在哪里。

例如

class AABB
{
  // ... members
  bool intersects( AABB other )
  {
    return other.left() < this->right() &&
           this->left() < other.right() &&

           // +y increases going down
           other.top() < this->bottom() &&
           this->top() < other.bottom() ;
  }
} ;

(vs)

class AABB
{
  bool intersects( AABB other )
  {
    return other.left() < right() &&
           left() < other.right() &&

           // +y increases going down
           other.top() < bottom() &&
           top() < other.bottom() ;
  }
} ;

AABB的right()指的是哪一个?这增加了一点澄清。

就我个人而言,我在引用成员变量时总是尝试使用这个。它有助于澄清代码并使其更具可读性。即使没有歧义,第一次阅读我的代码的人也不知道这一点,但如果他们看到始终使用这个,他们就会知道他们是否在查看成员变量。

每当我引用一个实例变量时,我都会使用它,即使我不需要。我认为这让代码更清晰。

我一有机会就用。我相信这会使代码更有可读性,而更有可读性的代码就等于更少的bug和更强的可维护性。

1 -常见的Java setter习语:

 public void setFoo(int foo) {
     this.foo = foo;
 }

2 -当调用以该对象作为参数的函数时

notifier.addListener(this);