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

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

问题描述

在从类本身访问类的实例变量或属性,你前面加上他们这一点。


< DIV CLASS =h2_lin>解决方案

没有。我认为这是视觉噪音。我觉得这个变量是一个拐杖坏的命名风格。在我喜欢的类型,我应该能够管理的字段,属性和方法的命名。



有绝对没有很好的理由来命名你的后盾场MyField的时,参数的构造函数MyField的与属性为MyField的。

 公共类识别TestClass 
{
私人字符串MyField的;
公众的TestClass(字符串MyField的)
{
this.myField = MyField的;
}
公共字符串MyField的{{返回MyField的;}集合{MyField的=值}}
}

就个人而言,我总是_前缀添加到所有我的私人支持字段。

 公共类识别TestClass 
{
私人字符串_myField;
公众的TestClass(字符串MyField的)
{
_myField = MyField的;
}
公共字符串MyField的{{返回_myField;}集合{_myField =值}}
}

和现在用C#自动属性。

 公共类识别TestClass 
{
私人字符串MyField的{搞定;设置;}
公众的TestClass(字符串MyField的)
{
MyField的= MyField的;
}
}



除了上面也许你键入唯一的其他时间这个。是因为你想看到您的当前类型的智能感知。如果你需要这样做,那么我认为你的类型太大,可能不按单一职责原则。并让说你是。为什么要保持这个的。经过周围你居然拨打电话。重构了出来。


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.

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

Personally, I always add a prefix of _ to all my private backing fields.

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

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.

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

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