When accessing instance variables or properties of a class from within the class itself, do you prepend them with "this.
"?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
It adds clutter. So no.
In C#, I absolutely do. The primary reasons are:
Whether to do it or not is a stylistic issue. In spite of all the fighting that goes on, I don't believe there's an objectively better approach.
My source analysis tool (StyleCop) defaults to requiring
this.
in front of instance accesses. My first point implies that I shouldn't care much about whether I always do or always don't, and because the default StyleCop setting is to always require it, I take the path of least resistance/greatest consistency and I follow the default setting.I follow this philosophy for most stylistic issues. I'm a huge fan of not changing default formatting options in an auto-formatting IDE. It just makes everyone's life harder over something that's really just not that important.
I think this practice improves legibility most of the time, so yes.
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".
Personally, I always add a prefix of _ to all my private backing fields.
and now with automatic properties in C#
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.
Absolutely. 'this' avoids the need for any prefixes, such as m_. More importantly, it quickly improves the performance of my code, and this is why:
I've really embraced the Microsoft Cops (FxCop, StyleCop). They've really helped me to catch things that normally I wouldn't even think about. For example, if a method does not reference any member variables, one suggestion from FxCop is to mark the method as static, so the method doesn't have to be allocated to every instance of the class. From MSDN:
Prefixing my member variables with 'this.' does two things for me. First, it satisfies StyleCop. Secondly, and more importantly, it helps me to quickly identify if a method needs to be marked static.
Of course, running FxCop will tell me if I need to mark a method as static. However, using 'this.' helps me spend more time writing new code and less time remedying FxCop violations.
I do, for me it adds a bit of clarity to the code, is it in the current procedure or the class?