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

在构造函数中:

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

在其他地方

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

当前回答

1 -常见的Java setter习语:

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

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

notifier.addListener(this);

其他回答

这个关键字在c#中有几种用法。

限定由相似名称隐藏的成员 将对象本身作为参数传递给其他方法 使对象从方法中返回自身 声明索引器 声明扩展方法 在构造函数之间传递参数 在内部重新分配值类型(struct)值。 在当前实例上调用扩展方法 转换为另一种类型 到同一类中定义的链构造函数

可以通过在作用域中不使用相同名称的成员变量和局部变量来避免第一种用法,例如通过遵循通用命名约定并使用属性(Pascal大小写)而不是字段(驼峰大小写)来避免与局部变量冲突(也是驼峰大小写)。在c# 3.0中,可以使用自动实现的属性轻松地将字段转换为属性。

1 -常见的Java setter习语:

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

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

notifier.addListener(this);

我养成了在Visual c++中大量使用它的习惯,因为这样做会触发智能感知,当我按'>'键时,我很懒。(而且容易出现错别字)

但我继续使用它,因为我发现它很方便,可以看到我调用的是成员函数而不是全局函数。

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

例如

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

在Jakub Šturc的回答中,他关于在构造器之间传递数据的第5条可能需要一些解释。这是在重载构造函数中,并且是强制使用This的一种情况。在下面的例子中,我们可以使用默认形参从无参数构造函数调用参数化构造函数。

class MyClass {
    private int _x
    public MyClass() : this(5) {}
    public MyClass(int v) { _x = v;}
}

我发现有时候这是一个特别有用的功能。