你什么时候使用“这个”关键词? [英] When do you use the "this" keyword?

查看:138
本文介绍了你什么时候使用“这个”关键词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇其他人如何使用关键字。我倾向于在构造函数中使用它,但我也可以在其他方法中使用它。例如:

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:

在构造函数中:

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

其他

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


推荐答案

a href =http://msdn.microsoft.com/en-us/library/dk1507sz.aspx =nofollow noreferrer> C 中的此关键字。

There are several usages of this keyword in C#.


  1. 要限定通过类似名称隐藏的成员

  2. 将对象作为其他方法的参数传递

  3. 使对象返回本身来自方法

  4. 声明索引器

  5. 声明扩展程序方法

  6. 在构造函数之间传递参数

  7. 要在内部重新分配值类型(struct)值

  8. 调用扩展方法

  9. 在同一类中定义的链构造函数

  1. To qualify members hidden by similar name
  2. To have an object pass itself as a parameter to other methods
  3. To have an object return itself from a method
  4. To declare indexers
  5. To declare extension methods
  6. To pass parameters between constructors
  7. To internally reassign value type (struct) value.
  8. To invoke an extension method on the current instance
  9. To cast itself to another type
  10. To chain constructors defined in the same class

您可以通过不使用具有相同名称的成员变量和局部变量来避免第一次使用,例如通过遵循常见的命名约定并使用属性(Pascal case)而不是字段(camel case),以避免与局部变量冲突驼峰盒)。在C#3.0字段中,可以使用自动实现的属性 a>。

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.

这篇关于你什么时候使用“这个”关键词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆