什么是一个好的规则,什么时候添加成员与'this'(C#)? [英] What is a good rule for when to prepend members with 'this' (C#)?

查看:128
本文介绍了什么是一个好的规则,什么时候添加成员与'this'(C#)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正在访问某个成员字段,属性或方法,我无法确定我应该在其前面加上this。

If I am accessing a member field, property, or method, I'm never sure when I should prepend it with 'this'.

关于需要它的情况,例如在局部变量具有相同名称的情况下。我在说的意思是完全一样的情况。哪个更可读?有没有任何标准,最佳做法或经验法则我应该遵循?

I am not asking about cases where it is required, like in the case where a local variable has the same name. I am talking about cases where the meaning is exactly the same. Which is more readable? Are there any standards, best practices, or rules of thumb I should be following? Should it just be consistent throughout a class, or an entire code base?

推荐答案

我建议使用Microsoft的指南,如StyleCop验证的那样: http://blogs.msdn.com/sourceanalysis/

I recommend using Microsoft's guidelines, as verified by StyleCop: http://blogs.msdn.com/sourceanalysis/

一般的规则是,用this前缀成员。

The general rule is, prepend members with "this." when they are defined in the class, unless they are static, in which case you cannot.

这里是直接来自StyleCop的规则:

Here is the rule directly from StyleCop:

SA1101: The call to {method or property name} must begin with the
'this.' prefix to indicate that the item is a member of the class.

这篇关于什么是一个好的规则,什么时候添加成员与'this'(C#)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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