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

在构造函数中:

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

在其他地方

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

当前回答

任何时候需要对当前对象的引用。

一个特别方便的场景是当对象调用一个函数并希望将自己传递给它时。

例子:

void onChange()
{
    screen.draw(this);
}

其他回答

任何时候需要对当前对象的引用。

一个特别方便的场景是当对象调用一个函数并希望将自己传递给它时。

例子:

void onChange()
{
    screen.draw(this);
}

这取决于我所遵循的编码标准。如果我们用_来表示一个实例变量,那么“this”就多余了。如果我们不使用_,那么我倾向于使用这个来表示实例变量。

this关键字的另一个很少使用的情况是,当您需要从实现类中调用显式接口实现时。这里有一个人为的例子:

class Example : ICloneable
{
    private void CallClone()
    {
        object clone = ((ICloneable)this).Clone();
    }

    object ICloneable.Clone()
    {
        throw new NotImplementedException();
    }
}

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

例如

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()指的是哪一个?这增加了一点澄清。

1 -常见的Java setter习语:

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

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

notifier.addListener(this);