I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
我很好奇其他人如何使用this关键字。我倾向于在构造函数中使用它,但我也可以在其他方法中使用它。一些例子:
In a constructor:
在构造函数中:
public Light(Vector v)
{
this.dir = new Vector(v);
}
Elsewhere
public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
31 个解决方案
#1
208
There are several usages of this keyword in C#.
C#中有几个关键字用法。
- To qualify members hidden by similar name
- To have an object pass itself as a parameter to other methods
- To have an object return itself from a method
- To declare indexers
- To declare extension methods
- To pass parameters between constructors
- To internally reassign value type (struct) value.
- To invoke an extension method on the current instance
- To cast itself to another type
- To chain constructors defined in the same class
限定隐藏类似名称的成员
让对象将自身作为参数传递给其他方法
使对象从方法返回自身
声明索引器
声明扩展方法
在构造函数之间传递参数
要在内部重新分配值类型(struct)值。
在当前实例上调用扩展方法
将自己投射到另一种类型
链接在同一个类中定义的构造函数
You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
您可以通过在作用域中不使用具有相同名称的成员和局部变量来避免第一次使用,例如通过遵循常见的命名约定并使用属性(Pascal case)而不是字段(camel case)来避免与局部变量(也是camel)发生冲突案件)。在C#3.0中,可以使用自动实现的属性轻松地将字段转换为属性。
#2
236
I don't mean this to sound snarky, but it doesn't matter.
我并不是说听起来很讽刺,但这并不重要。
Seriously.
Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.
看看重要的事情:你的项目,你的代码,你的工作,你的个人生活。他们中的任何一个都不会取决于您是否使用“this”关键字来限定对字段的访问权限。 this关键字无法帮助您准时发货。它不会减少错误,它不会对代码质量或可维护性产生任何明显的影响。它不会让你加薪,或者让你在办公室花更少的时间。
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.
我不会担心它。我会根据你自己的口味确保代码尽可能美观。如果你问10个程序员如何格式化代码,你将获得大约15种不同的意见。关注的一个更好的方法是如何将代码考虑在内。事情抽象得对吗?我选择了有意义的名字吗?是否有很多代码重复?有什么方法可以简化东西吗?我认为,正确处理这些事情将对您的项目,代码,工作和生活产生最大的积极影响。巧合的是,它可能也会导致另一个人抱怨最少。如果您的代码有效,易于阅读,并且考虑周全,那么另一个人就不会仔细检查如何初始化字段。他只是要使用你的代码,惊叹于它的伟大,然后转向别的东西。
#3
93
I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:
我只在绝对必要时使用它,即当另一个变量遮蔽另一个变量时。比如这里:
class Vector3
{
float x;
float y;
float z;
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)
或者正如Ryan Fox指出的那样,当你需要将此作为参数传递时。 (局部变量优先于成员变量)
#4
49
Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.
就个人而言,我在尝试引用成员变量时总是尝试使用它。它有助于澄清代码并使其更具可读性。即使没有歧义,有人第一次阅读我的代码并不知道,但如果他们看到这种情况一直使用,他们就会知道他们是否正在查看成员变量。
#5
37
I can't believe all of the people that say using it always is a "best practice" and such.
我无法相信所有使用它的人总是一个“最佳实践”等等。
Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.
当存在歧义时使用“this”,如Corey的示例中或当您需要将对象作为参数传递时,如Ryan的示例中所示。没有理由使用它,否则因为能够根据范围链解析变量应该足够清楚,因此使用它的限定变量应该是不必要的。
EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers
编辑:关于“this”的C#文档表示除了我提到的两个用于“this”关键字的另一个用途 - 用于声明索引器
EDIT: @Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.
编辑:@Juan:嗯,我没有看到我的陈述中有任何不一致 - 有三个实例我会使用“this”关键字(如C#文档中所述),而这些是你真正需要的时候。当没有阴影时,在构造函数中的变量前面粘贴“this”只是浪费击键而浪费我的时间阅读它,它没有任何好处。
#6
35
I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.
我每次引用实例变量时都会使用它,即使我不需要。我认为它使代码更清晰。
#7
#8
11
Any time you need a reference to the current object.
任何时候您需要对当前对象的引用。
One particularly handy scenario is when your object is calling a function and wants to pass itself into it.
一个特别方便的场景是当你的对象调用一个函数并希望将自己传递给它时。
Example:
void onChange()
{
screen.draw(this);
}
#9
6
I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.
我倾向于在任何地方使用它,只是为了确保它是我们正在处理的实例成员。
#10
5
I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.
我在任何可能存在歧义的地方使用它(显然)。不仅仅是编译器歧义(在这种情况下需要它),而且对于查看代码的人来说也是模棱两可的。
#11
5
Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:
this关键字的另一个有点罕见的用途是当您需要从实现类中调用显式接口实现时。这是一个人为的例子:
class Example : ICloneable
{
private void CallClone()
{
object clone = ((ICloneable)this).Clone();
}
object ICloneable.Clone()
{
throw new NotImplementedException();
}
}
#12
4
Here's when I use it:
这是我使用它的时候:
- Accessing Private Methods from within the class (to differentiate)
- Passing the current object to another method (or as a sender object, in case of an event)
- When creating extension methods :D
从类中访问私有方法(区分)
将当前对象传递给另一个方法(或者作为发件人对象,如果发生事件)
创建扩展方法时:D
I don't use this for Private fields because I prefix private field variable names with an underscore (_).
我不将此用于私有字段,因为我使用下划线(_)为私有字段变量名称添加前缀。
#13
4
[C++]
I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting this to always be there, i.e. they'll have to think about it.
我同意“必须时使用它”旅。用这个不必要地装饰代码并不是一个好主意,因为编译器在你忘记这样做时不会发出警告。这给那些期望永远存在的人带来了潜在的困惑,即他们必须考虑它。
So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are good things to do or otherwise):
那么,你什么时候使用它?我刚看了一些随机代码并发现了这些例子(我不会判断这些是好事还是其他):
- Passing "yourself" to a function.
- Assigning "yourself" to a pointer or something like that.
- Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.
- Compiler enforced disambiguation.
将“你自己”传递给一个函数。
将“你自己”分配给指针或类似的东西。
铸造,即上/下铸造(安全或其他),铸造常数等。
编译器强制消除歧义。
#14
3
I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.
我在一个接受对同一类型对象的引用的函数中使用它时,我想让它完全清楚我指的是哪个对象,在哪里。
For example
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() ;
}
} ;
At a glance which AABB does right()
refer to? The this
adds a bit of a clarifier.
一眼看出AABB做得对()是指?这增加了一点澄清。
#15
3
In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of this
is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.
在JakubŠturc的回答中,关于在构造函数之间传递数据的#5可能会使用一些解释。这是在重载构造函数,并且是必须使用它的一种情况。在下面的示例中,我们可以使用default参数从无参数构造函数中调用参数化构造函数。
class MyClass {
private int _x
public MyClass() : this(5) {}
public MyClass(int v) { _x = v;}
}
I've found this to be a particularly useful feature on occasion.
我发现这有时候是一个特别有用的功能。
#16
2
You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))
你应该总是使用它,我用它来区分私有字段和参数(因为我们的命名约定声明我们不使用成员和参数名称的前缀(并且它们基于互联网上的信息,所以我认为是最佳实践))
#17
2
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
我养成了在Visual C ++中*使用它的习惯,因为这样做会触发IntelliSense,我会点击'>'键,而且我很懒。 (并容易出现错别字)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
但是我继续使用它,因为我发现我正在调用成员函数而不是全局函数。
#18
1
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
我倾向于使用_来强调字段,所以不需要使用它。 R#也倾向于重构它们......
#19
1
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
我几乎只在引用同一类型内部的类型属性时才使用它。正如另一位用户所提到的,我也强调了本地字段,因此它们很明显而不需要这样。
#20
1
I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:
我只在需要时才使用它,除了由于单个参数多态性而必须将其放入一方的方法中的对称操作:
boolean sameValue (SomeNum other) {
return this.importantValue == other.importantValue;
}
#21
1
[C++]
this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:
这用于赋值运算符,大多数时候你必须检查并防止奇怪的(无意的,危险的,或者只是浪费时间用于程序)这样的事情:
A a;
a = a;
Your assignment operator will be written:
您的作业运算符将被写入:
A& A::operator=(const A& a) {
if (this == &a) return *this;
// we know both sides of the = operator are different, do something...
return *this;
}
#22
1
this
on a C++ compiler
The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
如果符号没有立即找到,C ++编译器将静默查找符号。有时候,大部分时间都是好的:
- using the mother class' method if you did not overloaded it in the child class.
- promoting a value of a type into another type
如果你没有在子类中重载它,请使用母类的方法。
将类型的值提升为另一种类型
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
但有时候,你只是不想让编译器猜测。您希望编译器选择正确的符号而不是另一个符号。
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf
instead of print
. this->printf
would not have compiled.
对我来说,那些时间是在方法中,我想要访问成员方法或成员变量。我只是不想因为我写了printf而不是print而选择了一些随机符号。 this-> printf不会编译。
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
问题在于,使用C遗留库(§),多年前编写的遗留代码(§§),或者在复制/粘贴是过时但仍然活跃的特性的语言中发生的任何事情,有时会告诉编译器不要播放智慧是个好主意。
These are the reasons I use this
.
这些是我使用它的原因。
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§)它对我来说仍然是一个谜,但我现在想知道你的源中包含
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
(§§)意识到“你需要包含一个标题,但包括这个标题将会破坏你的代码,因为它使用了一些带有通用名称的哑巴宏”是编码器生命中的俄罗斯轮盘时刻之一
#23
1
I use it to invoke Intellisense just like JohnMcG, but I'll go back and erase "this->" when I'm done. I follow the Microsoft convention of prefixing member variables with "m_", so leaving it as documentation would just be redundant.
我像JohnMcG一样使用它来调用Intellisense,但是当我完成时我会回去并删除“this->”。我遵循Microsoft使用“m_”为成员变量添加前缀的约定,因此将其作为文档保留将是多余的。
#24
1
'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).
'这个。'帮助找到有很多成员的'this'类的成员(通常是由于深度继承链)。
Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.
点击CTRL + Space对此没有帮助,因为它还包括类型;在哪里 - 就像'这个'。仅包括会员。
I usually delete it once I have what I was after: but this is just my style breaking through.
一旦我拥有了我所追求的东西,我通常会将其删除:但这只是我突破的风格。
In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.
在风格方面,如果你是一个独行侠 - 你决定;如果你为公司工作坚持公司政策(看看源代码管理中的东西,看看其他人在做什么)。在使用它来限定成员资格方面,无论是对还是错。唯一错误的是不一致 - 这是风格的黄金法则。留下挑选他人。花时间思考真正的编码问题 - 显然是编码 - 而不是。
#25
0
It depends on the coding standard I'm working under. If we are using _ to denote an instance variable then "this" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.
这取决于我正在使用的编码标准。如果我们使用_来表示实例变量,那么“this”就变得多余了。如果我们不使用_那么我倾向于使用它来表示实例变量。
#26
0
1 - Common Java setter idiom:
1 - 常见的Java setter习语:
public void setFoo(int foo) {
this.foo = foo;
}
2 - When calling a function with this object as a parameter
2 - 使用此对象作为参数调用函数时
notifier.addListener(this);
#27
0
I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.
我每次都用它。我相信它使代码更具可读性,更易读的代码等于更少的错误和更多的可维护性。
#28
0
When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.
当您有许多开发人员在相同的代码库上工作时,您需要一些代码指南/规则。在我工作的地方,我们决定在字段,属性和事件上使用'this'。
To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.
对我而言,这样做很有意义,当你区分类变量和方法变量时,它使代码更容易阅读。
#29
0
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
有一种用法在C ++中尚未提及,那就是不要引用自己的对象或者从接收到的变量中消除成员的歧义。
You can use this
to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.
您可以使用它将非依赖名称转换为从其他模板继承的模板类中的参数依赖名称。
template <typename T>
struct base {
void f() {}
};
template <typename T>
struct derived : public base<T>
{
void test() {
//f(); // [1] error
base<T>::f(); // quite verbose if there is more than one argument, but valid
this->f(); // f is now an argument dependent symbol
}
}
Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
模板使用双向机制进行编译。在第一次传递期间,仅解析和检查非参数依赖名称,而仅检查依赖名称的一致性,而不实际替换模板参数。
At that step, without actually substituting the type, the compiler has almost no information of what base<T>
could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f
that seems just natural to the programmer is a symbol that the compiler must find as a member of derived
or in enclosing namespaces --which does not happen in the example-- and it will complain.
在那一步,在没有实际替换类型的情况下,编译器几乎没有关于base
The solution is turning the non-dependent name f
into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f
--adding the base<T>
makes the symbol dependent on T
and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.
解决方案是将非依赖名称f转换为依赖名称。这可以通过两种方式完成,方法是明确说明实现它的类型(base
The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this->
before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>
) this->
is argument dependent, and we get the same result: this->f
is checked in the second round, after template parameter substitution.
第二种方式,如果你从具有多个参数的模板或长名称继承的话,那么只需要在符号之前添加this->。由于你实现的模板类确实依赖于一个参数(它继承自base
#30
-1
You should not use "this" unless you absolutely must.
除非绝对必要,否则不应使用“this”。
There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.
有一个与不必要的冗长相关的惩罚。您应该努力寻找完全符合需要的代码,而不再是代码。
#1
208
There are several usages of this keyword in C#.
C#中有几个关键字用法。
- To qualify members hidden by similar name
- To have an object pass itself as a parameter to other methods
- To have an object return itself from a method
- To declare indexers
- To declare extension methods
- To pass parameters between constructors
- To internally reassign value type (struct) value.
- To invoke an extension method on the current instance
- To cast itself to another type
- To chain constructors defined in the same class
限定隐藏类似名称的成员
让对象将自身作为参数传递给其他方法
使对象从方法返回自身
声明索引器
声明扩展方法
在构造函数之间传递参数
要在内部重新分配值类型(struct)值。
在当前实例上调用扩展方法
将自己投射到另一种类型
链接在同一个类中定义的构造函数
You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
您可以通过在作用域中不使用具有相同名称的成员和局部变量来避免第一次使用,例如通过遵循常见的命名约定并使用属性(Pascal case)而不是字段(camel case)来避免与局部变量(也是camel)发生冲突案件)。在C#3.0中,可以使用自动实现的属性轻松地将字段转换为属性。
#2
236
I don't mean this to sound snarky, but it doesn't matter.
我并不是说听起来很讽刺,但这并不重要。
Seriously.
Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.
看看重要的事情:你的项目,你的代码,你的工作,你的个人生活。他们中的任何一个都不会取决于您是否使用“this”关键字来限定对字段的访问权限。 this关键字无法帮助您准时发货。它不会减少错误,它不会对代码质量或可维护性产生任何明显的影响。它不会让你加薪,或者让你在办公室花更少的时间。
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.
我不会担心它。我会根据你自己的口味确保代码尽可能美观。如果你问10个程序员如何格式化代码,你将获得大约15种不同的意见。关注的一个更好的方法是如何将代码考虑在内。事情抽象得对吗?我选择了有意义的名字吗?是否有很多代码重复?有什么方法可以简化东西吗?我认为,正确处理这些事情将对您的项目,代码,工作和生活产生最大的积极影响。巧合的是,它可能也会导致另一个人抱怨最少。如果您的代码有效,易于阅读,并且考虑周全,那么另一个人就不会仔细检查如何初始化字段。他只是要使用你的代码,惊叹于它的伟大,然后转向别的东西。
#3
93
I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:
我只在绝对必要时使用它,即当另一个变量遮蔽另一个变量时。比如这里:
class Vector3
{
float x;
float y;
float z;
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)
或者正如Ryan Fox指出的那样,当你需要将此作为参数传递时。 (局部变量优先于成员变量)
#4
49
Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.
就个人而言,我在尝试引用成员变量时总是尝试使用它。它有助于澄清代码并使其更具可读性。即使没有歧义,有人第一次阅读我的代码并不知道,但如果他们看到这种情况一直使用,他们就会知道他们是否正在查看成员变量。
#5
37
I can't believe all of the people that say using it always is a "best practice" and such.
我无法相信所有使用它的人总是一个“最佳实践”等等。
Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.
当存在歧义时使用“this”,如Corey的示例中或当您需要将对象作为参数传递时,如Ryan的示例中所示。没有理由使用它,否则因为能够根据范围链解析变量应该足够清楚,因此使用它的限定变量应该是不必要的。
EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers
编辑:关于“this”的C#文档表示除了我提到的两个用于“this”关键字的另一个用途 - 用于声明索引器
EDIT: @Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.
编辑:@Juan:嗯,我没有看到我的陈述中有任何不一致 - 有三个实例我会使用“this”关键字(如C#文档中所述),而这些是你真正需要的时候。当没有阴影时,在构造函数中的变量前面粘贴“this”只是浪费击键而浪费我的时间阅读它,它没有任何好处。
#6
35
I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.
我每次引用实例变量时都会使用它,即使我不需要。我认为它使代码更清晰。
#7
27
I use it whenever StyleCop tells me to. StyleCop must be obeyed. Oh yes.
我会在StyleCop告诉我的时候使用它。必须遵守StyleCop。哦,是的。
#8
11
Any time you need a reference to the current object.
任何时候您需要对当前对象的引用。
One particularly handy scenario is when your object is calling a function and wants to pass itself into it.
一个特别方便的场景是当你的对象调用一个函数并希望将自己传递给它时。
Example:
void onChange()
{
screen.draw(this);
}
#9
6
I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.
我倾向于在任何地方使用它,只是为了确保它是我们正在处理的实例成员。
#10
5
I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.
我在任何可能存在歧义的地方使用它(显然)。不仅仅是编译器歧义(在这种情况下需要它),而且对于查看代码的人来说也是模棱两可的。
#11
5
Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:
this关键字的另一个有点罕见的用途是当您需要从实现类中调用显式接口实现时。这是一个人为的例子:
class Example : ICloneable
{
private void CallClone()
{
object clone = ((ICloneable)this).Clone();
}
object ICloneable.Clone()
{
throw new NotImplementedException();
}
}
#12
4
Here's when I use it:
这是我使用它的时候:
- Accessing Private Methods from within the class (to differentiate)
- Passing the current object to another method (or as a sender object, in case of an event)
- When creating extension methods :D
从类中访问私有方法(区分)
将当前对象传递给另一个方法(或者作为发件人对象,如果发生事件)
创建扩展方法时:D
I don't use this for Private fields because I prefix private field variable names with an underscore (_).
我不将此用于私有字段,因为我使用下划线(_)为私有字段变量名称添加前缀。
#13
4
[C++]
I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting this to always be there, i.e. they'll have to think about it.
我同意“必须时使用它”旅。用这个不必要地装饰代码并不是一个好主意,因为编译器在你忘记这样做时不会发出警告。这给那些期望永远存在的人带来了潜在的困惑,即他们必须考虑它。
So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are good things to do or otherwise):
那么,你什么时候使用它?我刚看了一些随机代码并发现了这些例子(我不会判断这些是好事还是其他):
- Passing "yourself" to a function.
- Assigning "yourself" to a pointer or something like that.
- Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.
- Compiler enforced disambiguation.
将“你自己”传递给一个函数。
将“你自己”分配给指针或类似的东西。
铸造,即上/下铸造(安全或其他),铸造常数等。
编译器强制消除歧义。
#14
3
I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.
我在一个接受对同一类型对象的引用的函数中使用它时,我想让它完全清楚我指的是哪个对象,在哪里。
For example
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() ;
}
} ;
At a glance which AABB does right()
refer to? The this
adds a bit of a clarifier.
一眼看出AABB做得对()是指?这增加了一点澄清。
#15
3
In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of this
is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.
在JakubŠturc的回答中,关于在构造函数之间传递数据的#5可能会使用一些解释。这是在重载构造函数,并且是必须使用它的一种情况。在下面的示例中,我们可以使用default参数从无参数构造函数中调用参数化构造函数。
class MyClass {
private int _x
public MyClass() : this(5) {}
public MyClass(int v) { _x = v;}
}
I've found this to be a particularly useful feature on occasion.
我发现这有时候是一个特别有用的功能。
#16
2
You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))
你应该总是使用它,我用它来区分私有字段和参数(因为我们的命名约定声明我们不使用成员和参数名称的前缀(并且它们基于互联网上的信息,所以我认为是最佳实践))
#17
2
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
我养成了在Visual C ++中*使用它的习惯,因为这样做会触发IntelliSense,我会点击'>'键,而且我很懒。 (并容易出现错别字)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
但是我继续使用它,因为我发现我正在调用成员函数而不是全局函数。
#18
1
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
我倾向于使用_来强调字段,所以不需要使用它。 R#也倾向于重构它们......
#19
1
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
我几乎只在引用同一类型内部的类型属性时才使用它。正如另一位用户所提到的,我也强调了本地字段,因此它们很明显而不需要这样。
#20
1
I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:
我只在需要时才使用它,除了由于单个参数多态性而必须将其放入一方的方法中的对称操作:
boolean sameValue (SomeNum other) {
return this.importantValue == other.importantValue;
}
#21
1
[C++]
this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:
这用于赋值运算符,大多数时候你必须检查并防止奇怪的(无意的,危险的,或者只是浪费时间用于程序)这样的事情:
A a;
a = a;
Your assignment operator will be written:
您的作业运算符将被写入:
A& A::operator=(const A& a) {
if (this == &a) return *this;
// we know both sides of the = operator are different, do something...
return *this;
}
#22
1
this
on a C++ compiler
The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
如果符号没有立即找到,C ++编译器将静默查找符号。有时候,大部分时间都是好的:
- using the mother class' method if you did not overloaded it in the child class.
- promoting a value of a type into another type
如果你没有在子类中重载它,请使用母类的方法。
将类型的值提升为另一种类型
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
但有时候,你只是不想让编译器猜测。您希望编译器选择正确的符号而不是另一个符号。
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf
instead of print
. this->printf
would not have compiled.
对我来说,那些时间是在方法中,我想要访问成员方法或成员变量。我只是不想因为我写了printf而不是print而选择了一些随机符号。 this-> printf不会编译。
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
问题在于,使用C遗留库(§),多年前编写的遗留代码(§§),或者在复制/粘贴是过时但仍然活跃的特性的语言中发生的任何事情,有时会告诉编译器不要播放智慧是个好主意。
These are the reasons I use this
.
这些是我使用它的原因。
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§)它对我来说仍然是一个谜,但我现在想知道你的源中包含
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
(§§)意识到“你需要包含一个标题,但包括这个标题将会破坏你的代码,因为它使用了一些带有通用名称的哑巴宏”是编码器生命中的俄罗斯轮盘时刻之一
#23
1
I use it to invoke Intellisense just like JohnMcG, but I'll go back and erase "this->" when I'm done. I follow the Microsoft convention of prefixing member variables with "m_", so leaving it as documentation would just be redundant.
我像JohnMcG一样使用它来调用Intellisense,但是当我完成时我会回去并删除“this->”。我遵循Microsoft使用“m_”为成员变量添加前缀的约定,因此将其作为文档保留将是多余的。
#24
1
'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).
'这个。'帮助找到有很多成员的'this'类的成员(通常是由于深度继承链)。
Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.
点击CTRL + Space对此没有帮助,因为它还包括类型;在哪里 - 就像'这个'。仅包括会员。
I usually delete it once I have what I was after: but this is just my style breaking through.
一旦我拥有了我所追求的东西,我通常会将其删除:但这只是我突破的风格。
In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.
在风格方面,如果你是一个独行侠 - 你决定;如果你为公司工作坚持公司政策(看看源代码管理中的东西,看看其他人在做什么)。在使用它来限定成员资格方面,无论是对还是错。唯一错误的是不一致 - 这是风格的黄金法则。留下挑选他人。花时间思考真正的编码问题 - 显然是编码 - 而不是。
#25
0
It depends on the coding standard I'm working under. If we are using _ to denote an instance variable then "this" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.
这取决于我正在使用的编码标准。如果我们使用_来表示实例变量,那么“this”就变得多余了。如果我们不使用_那么我倾向于使用它来表示实例变量。
#26
0
1 - Common Java setter idiom:
1 - 常见的Java setter习语:
public void setFoo(int foo) {
this.foo = foo;
}
2 - When calling a function with this object as a parameter
2 - 使用此对象作为参数调用函数时
notifier.addListener(this);
#27
0
I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.
我每次都用它。我相信它使代码更具可读性,更易读的代码等于更少的错误和更多的可维护性。
#28
0
When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.
当您有许多开发人员在相同的代码库上工作时,您需要一些代码指南/规则。在我工作的地方,我们决定在字段,属性和事件上使用'this'。
To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.
对我而言,这样做很有意义,当你区分类变量和方法变量时,它使代码更容易阅读。
#29
0
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
有一种用法在C ++中尚未提及,那就是不要引用自己的对象或者从接收到的变量中消除成员的歧义。
You can use this
to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.
您可以使用它将非依赖名称转换为从其他模板继承的模板类中的参数依赖名称。
template <typename T>
struct base {
void f() {}
};
template <typename T>
struct derived : public base<T>
{
void test() {
//f(); // [1] error
base<T>::f(); // quite verbose if there is more than one argument, but valid
this->f(); // f is now an argument dependent symbol
}
}
Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
模板使用双向机制进行编译。在第一次传递期间,仅解析和检查非参数依赖名称,而仅检查依赖名称的一致性,而不实际替换模板参数。
At that step, without actually substituting the type, the compiler has almost no information of what base<T>
could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f
that seems just natural to the programmer is a symbol that the compiler must find as a member of derived
or in enclosing namespaces --which does not happen in the example-- and it will complain.
在那一步,在没有实际替换类型的情况下,编译器几乎没有关于base
The solution is turning the non-dependent name f
into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f
--adding the base<T>
makes the symbol dependent on T
and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.
解决方案是将非依赖名称f转换为依赖名称。这可以通过两种方式完成,方法是明确说明实现它的类型(base
The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this->
before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>
) this->
is argument dependent, and we get the same result: this->f
is checked in the second round, after template parameter substitution.
第二种方式,如果你从具有多个参数的模板或长名称继承的话,那么只需要在符号之前添加this->。由于你实现的模板类确实依赖于一个参数(它继承自base
#30
-1
You should not use "this" unless you absolutely must.
除非绝对必要,否则不应使用“this”。
There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.
有一个与不必要的冗长相关的惩罚。您应该努力寻找完全符合需要的代码,而不再是代码。