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

在构造函数中:

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

在其他地方

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

当前回答

除非万不得已,否则不要用this。

不必要的冗长是有惩罚的。您应该努力使代码的长度恰好与需要的长度相同,而不是更长。

其他回答

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

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

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

你应该经常使用它,我用它来区分私有字段和参数(因为我们的命名约定声明我们不为成员和参数名使用前缀(并且它们是基于在互联网上找到的信息,所以我认为这是一个最佳实践))

“这。'帮助查找'this'类中有很多成员的成员(通常是由于深度继承链)。

按CTRL+空格键并没有帮助,因为它还包括类型;而这。’只包括会员。

一旦我得到我想要的东西,我通常会删除它:但这只是我风格的突破。

在风格方面,如果你是一个独行侠——你决定;如果你在一家公司工作,坚持公司的政策(看看源代码控制中的东西,看看其他人在做什么)。就用它来评定成员资格而言,既不正确也不错误。唯一错误的就是前后矛盾——这是风格的黄金法则。别挑剔别人。把时间花在思考真正的编码问题上——当然还有编码。

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

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

例子:

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

我并不想这么说,但这并不重要。

认真对待。

看看那些重要的东西:你的项目,你的代码,你的工作,你的个人生活。它们中的任何一个都不会成功依赖于是否使用“this”关键字来限定对字段的访问。这个关键字不会帮助你按时发货。它不会减少bug,也不会对代码质量或可维护性产生明显的影响。它不会让你加薪,也不会让你在办公室花更少的时间。

It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.

I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.