当你使用"本"关键词? [英] When do you use the "this" keyword?

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

问题描述

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

在一个构造器:

 公共小巴(矢量V)
{
    this.dir =新的向量(V);
}

在别处

 公共无效的someMethod()
{
    向量VEC =新的向量();
    双D =(VEC * VEC) - (this.radius * this.radius);
}


解决方案

这个 C#中的关键字。


  1. 要符合会员通过类似的名字隐藏

  2. 为了有一个对象通过自身作为参数传递给其他方法

  3. 要具有对象的方法返回其自身

  4. 要声明索引

  5. 要声明的扩展方法

  6. 要通过构造 <之间的参数/ LI>
  7. To内部重新分配值类型(结构)值

  8. 要在当前实例调用扩展方法

  9. 要投自己为另一种类型

  10. 要在同一类 <定义构造函数链/ LI>

可以通过不具有在范围相同名称构件和局部变量,例如,通过下列通用命名约定和使用性能(帕斯卡的情况),而不是字段(骆驼情况下),以避免与局部变量碰撞避免第一使用(也驼的情况下)。在C#3.0的字段可以很容易地通过使用自动实现属性

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:

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

解决方案

There are several usages of this keyword in C#.

  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

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.

这篇关于当你使用&QUOT;本&QUOT;关键词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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