C# 你什么时候使用“this”关键字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When do you use the "this" keyword?
提问by ftdysa
I was curious about how other people use the thiskeyword. 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);
}
采纳答案by Jakub ?turc
There are several usages of thiskeyword 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
- 限定被相似名称隐藏的成员
- 让对象将自身作为参数传递给其他方法
- 让对象从方法返回自身
- 声明索引器
- 声明扩展方法
- 在构造函数之间传递参数
- 在内部重新分配值类型(结构) value。
- 在当前实例上调用扩展方法
- 将自身强制转换为另一种类型
- 链接在同一类中定义的构造函数
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 中,字段可以通过使用自动实现的属性轻松转换为属性。
回答by Thomas Owens
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.
我每次引用实例变量时都会使用它,即使我不需要。我认为它使代码更清晰。
回答by TheSmurf
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.
我在任何可能存在歧义的地方使用它(显然)。不仅仅是编译器的歧义(在那种情况下是必需的),还有查看代码的人的歧义。
回答by JamesSugrue
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
我倾向于用 _ 在字段下划线,所以真的不需要使用它。无论如何,R# 也倾向于重构它们......
回答by juan
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))
你应该总是使用它,我用它来区分私有字段和参数(因为我们的命名约定声明我们不使用成员和参数名称的前缀(并且它们基于在 Internet 上找到的信息,所以我认为最佳实践))
回答by Corey
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 指出的那样,当您需要将其作为参数传递时。(局部变量优先于成员变量)
回答by Ryan Fox
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);
}
回答by akmad
I pretty much only use thiswhen 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.
我几乎只在从同一类型内部引用类型属性时才使用它。正如另一位用户所提到的,我还强调了本地字段,因此它们在不需要this 的情况下也很明显。
回答by Dan Blair
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”就变得多余了。如果我们不使用 _ 那么我倾向于使用它来表示实例变量。
回答by Philippe
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.
我也倾向于在任何地方使用它,只是为了确保我们正在处理的是实例成员。
回答by Jason Bunting
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 exampleor 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 needit. 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:嗯,我的陈述中没有任何不一致之处 - 有 3 次我会使用“this”关键字(如 C# 文档中所述),而那些是您实际需要它的时候。在没有阴影的情况下,将“this”放在构造函数中的变量前面只是浪费击键和阅读它的时间,它没有任何好处。