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

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

问题描述

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

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);
}

推荐答案

this 关键字.

  1. 限定被相似隐藏的成员姓名
  2. 让对象本身通过作为其他方法的参数
  3. 让对象从方法返回自身
  4. 声明索引器
  5. 声明扩展方法
  6. 在构造函数之间传递参数
  7. 内部重新分配值类型(结构)值.
  8. 在当前实例上调用扩展方法
  9. 将自身转换为另一种类型
  10. 链接同一类中定义的构造函数

您可以通过不在作用域中使用同名的成员变量和局部变量来避免第一次使用,例如通过遵循常见的命名约定并使用属性(Pascal case)而不是字段(camel case)来避免与局部变量发生冲突(还有骆驼套).在 C# 3.0 中,可以使用 自动实现的属性.

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天全站免登陆