我应该使用`默认this`? [英] Should I be using `this` by default?

查看:143
本文介绍了我应该使用`默认this`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道,这个是指一类的实际的实例...但它的大多数人都没有用在我看来。 ?所以,我应该使用它

We all know that this refers to the actual instance of a class...but it seems to me that most people are not using it. So, should I be using it?

是我关于它的想法如下:由于这个指实际一个类的实例,它应该被用来访问类的任何成员。

My thoughts about it are as follows: Since this refers to the actual instance of a class, it should be used to access any member of that class.

  public void(String newValue) {
        this.privateVariable = newValue;
  }

这应保证的值没有被分配到一个对象具有相同名称范围(这也可能最终成为未定义行为,反正)之内。但是,如果有什么下划线用于从非私营领域独立的私人:

This should guarantee that the value is not assigned to an object with the same name within the scope (which could also end up as undefined behavior, anyway). But, what if an underscore is used to separate private from non-private fields:

  public voud(String newValue) {
        _privateVariable = newValue;
  }



这个似乎这种情况下,一点点多余的和不必要的。

this seems in that case a little redundant and unnecessary.

那么,有没有很好的理由使用或不使用这个?还是我只是货架我无事的大脑?

So, are there good reasons to use or not use this? Or am I just racking my brain about nothing?

推荐答案

我个人只当它是必要的,例如,使用它

Personally I only use it when it's necessary, e.g.

public MyClass(string name)
{
    this.name = name;
}



我更喜欢从最自然的名称重命名参数或字段。我不使用这个其中,这是不必要的,否则虽然。话虽如此,但绝对没有的危害的这样做 - 如果你觉得它使你的代码更清晰,这是一个很好的理由来使用它。

I prefer that to renaming the parameter or field from the most natural name. I don't use this where it's otherwise unnecessary though. Having said that, there's absolutely no harm in doing so - and if you feel that it makes your code clearer, that's a very good reason to use it.

这篇关于我应该使用`默认this`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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