在 C# 中使用 this 关键字的优点和缺点
在编程中,您可以使用 this 关键字
this.Textbox
或只是
Textbox
最佳实践是什么?
我看到的一些好处是,使用它可以更容易地在智能感知中看到,并更容易理解它是一个属性。
目前我不使用这个...我在某处的一些文章中读到该人删除了所有引用,但我不记得为什么。
使用 this 关键字有什么优点和缺点?
In programming you can use the this keyword
this.Textbox
or just
Textbox
What is the best practice?
Some benefits I can see is that using this makes it easier to see in intellisense and makes it easier to understand that it is a property.
Currently I don't use this... I read in some article somewhere that the guy removed all the references, but I don't remember why.
What are the pros and cons of using the this keyword?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
系统地使用
this
意味着您不会陷入引用局部变量的陷阱,而实际上您需要this
的成员。缺点:使用
this
会让你的代码更加冗长。这确实取决于个人喜好。
Using
this
systematically will mean that you don't fall into a trap of referring to a local variable when in fact you want a member ofthis
.The downside: using
this
will make your code more verbose.It's really up to personal preference.
唯一的缺点是打字比较多。使用
this
(尤其是一致地)还可以排除例如在您打算使用属性时使用参数,例如方法f(Textbox textbox) =>; {textbox = textbox}
当您想说this.Textbox = textbox.
时,始终如一地使用它不仅会使您无法做到这一点,而且还会使其在您可能做到的时候脱颖而出。The only cons are that it is more typing. Using
this
(esp. consistently) also precludes, for example, using a parameter when you meant to use a property, e.g. a methodf(Textbox textbox) => {textbox = textbox}
when you meant to saythis.Textbox = textbox.
Using it consistently not only makes it impossible to do so but also makes it stand out when you possibly could have.这确实是一个偏好问题。有时您必须使用
this
关键字,在这种情况下:没有
this
将导致参数仅将自身设置为自身的错误。它不太冗长,但有些人可能会说它也不太清晰(因此是首选)。It's a matter of preference, really. Sometimes you have to use the
this
keyword, in cases like this:Not having the
this
will result in a bug where the parameter just sets itself to itself. It's less verbose, but some may say it's also less clear (hence preference).我更喜欢省略
this.
,因为这样可以减少打字次数,减少混乱,并且仅在必要时使用它,否则标识符会不明确。作为旁注,我喜欢 Cobra 中处理成员访问的方式。它要求它们以
.
为前缀(或私有的_
)。因此,您可以使用.member=parameter
。第一个显然是成员,第二个是局部变量。这是一种消除歧义而不变得冗长的优雅方法。I prefer leaving out
this.
because it's less typing and less clutter and only use it when necessary because the identifier would be ambiguous otherwise.As a sidenote I like the way member acces is handled in Cobra. It requires them to be prefixed with a
.
(or_
for privates). So you'd use.member=parameter
. And the first is obviously a member and the second a local variable. An elegant way to remove the ambiguity without becoming verbose.我刚刚开始删除这个。来自代码库的限定结果已经出现:
扩展方法必须有一个this。前缀!
因此,除非这样,否则扩展方法的使用并不透明。一般使用资格。
I've just started to remove this. qualification from a codebase which has turned up a consequence:
Extension methods must have a this. prefix!
Thus, use of extension methods isn't transparent unless this. qualification is used generally.