你在实例变量前面使用“this”吗? [英] Do you use 'this' in front of instance variables?

查看:147
本文介绍了你在实例变量前面使用“this”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从类本身访问类的实例变量或属性时,是否使用 this。前缀?

When accessing instance variables or properties of a class from within the class itself, do you prepend them with "this."?

推荐答案

否。我认为它是视觉噪声。我认为这个变量是一个错误的命名风格的拐杖。在我的类型中,我应该能够管理字段,属性和方法的命名。

No. I consider it visual noise. I think the this variable is a crutch to bad naming styles. Within my type I should be able to manage the naming of the fields, properties and methods.

没有什么好的理由来命名你的支持字段myfield,参数为构造函数为myField,属性为myField。

There is absolutely no good reason to name your backing field "myfield", the parameter to the constructor as "myField" and the property to be "myField".

 public class TestClass
 {
    private string myField;
    public TestClass(string myField)
    {
      this.myField = myField;
    }
    public string MyField {get { return myField;} set {myField = value}}
 }

$

 public class TestClass
 {
    private string _myField;
    public TestClass(string myField)
    {
      _myField = myField;
    }
    public string MyField {get { return _myField;} set {_myField = value}}
 }

现在在C#中有自动属性

and now with automatic properties in C#

 public class TestClass
 {
    private string MyField {get; set;}
    public TestClass(string myField)
    {
      MyField = myField;
    }
 }

这个。是因为你想看到当前类型的智能感知。如果您需要这样做,那么我提交您的类型太大,可能不遵循单一责任原则。让我们说你是。为什么保持这一点。在你实际打电话后。重构它。

Other than the above maybe the only other time you type this. is because you want to see the intellisense for your current type. If you need to do this then I submit that your type is too big and probably not following the Single Responsibility Principle. And lets say you are. Why keep the this. around after you actually make the call. Refactor it out.

这篇关于你在实例变量前面使用“this”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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