C# StyleCop - Using “this.” prefix for base class members like current class members or not?

点点圈 提交于 2019-12-05 03:32:23

The documentation for StyleCop Rule SA1101 actually mentions this:

A violation of this rule occurs whenever the code contains a call to an instance member of the local class or a base class which is not prefixed with ‘this.’.

(emphasis added by myself). So yes, the rule requires this. on every access to an instance member, irrespective of whether that member is in the local class or inherited from a base class.

If you think about the rules for object inheritance, even though F1() is actually declared on BaseClass it is inherited by ChildClass so it is valid to call it as this.F1(). This is what StyleCop is telling you to do. By prefixing the call with this, it becomes unambiguous that you are calling the F1() instance method of the current runtime instance of the class.

In fact, calling it as F1() or this.F1() are actually synonymous, but the meaning/intent becomes clearer when using the this prefix.

You should not use the base prefix here at all (even though it will compile) because F1() is not virtual and being overridden in ChildClass. The only reason to use the base prefix is when you have overridden a virtual base class member and want to explicitly call that base class member from within the overriding member. If you did actually use the base prefix without F1() being virtual everything would actually work until you made F1() virtual and added an override in ChildClass. At that point, any calls to base.F1() would continue calling BaseClass.F1() and not the new override in ChildClass.

I believe that is correct since the rule holds for all methods regardless of whether they are defined on the base or not. Personally I am not a huge fan of this rule so I just disable it.

I like to use base. base.F1() for your case. That prevents accidently referencing a local variable, and is a visual reminder of where the member came from.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!