开发者

Why VS uses "this" so often? [duplicate]

This question already has answers here: When do you use the "this" keyword? [closed] (31 answers) Closed 9 years ago.

I know what "this" keyword serves for but do no开发者_Go百科t udnerstand why VS uses it nearly always, like this.Invalidate. If the call is placed within the class and there is no problem with identifier, what is it good for?


It is not VS who uses it but the developers who do. If you use a tool like Resharper, it always points out where "this" is unnecessary or redundant.


I think it's mainly a question of style. Using the this reference makes it 100% clear what you intend to reference.

You say there is no problem with the identifier (in that there is no clash of names in scope), but that doesn't mean there won't be in the future.

Additional names or classes could be added to an outer scope. It's unlikely and probably wouldn't cause a problem anyway, but it helps to remove any possibility of ambiguity.


It explicitly shows that this variable or method belongs to this class. It more readable. Its not mandatory though. Its up to the developer and the team to decide whether they want to use it this way or not. It's just another code style.


If the call is placed within the class and there is no problem with identifier, what is it good for?

I assume your talking about autogenerated code, from e.g. the forms designer. It could

a) be written to analyse the code it's already emitted, decide whether the identifier is ambiguous, and then based on that, decide whether to use this. to properly qualify the name, or,

b) just use this. for all class-scoped identifiers.


It may seem redundant in many cases, but the exact same IL code will be produced whether or not you use this. in an unambiguous context, so it's not as if it's causing any harm to always include it.


Adding this, in unnecessary cases, reduces your code's complexity and makes it more readable.


Hahaha, because if you use "this." then Intellisense pops up and you have all your class members at your disposal and don't have to type so much (or make so many typos, whatever...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜