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

早过忘川 提交于 2019-12-22 04:36:09

问题


StyleCop has a rule about using "this." prefix to calling class members (SA1101).

Is this rule holds true about a member (for example a method) of a class which is inherited from its base class.

Example:

class BaseClass
{
    protected void F1()
    {
        ...
    }
}    

class ChildClass : BaseClass
{
    protected void F2()
    {
        ...
    }

    protected void F3()
    {
        this.F2(); // This is correct acording to SA1101

        // F1 is a member of base class and if I dont put this prefix, stylecop will not show any message.
        this.F1(); // Is this correct?
        F1();      // Or this?
    }
}

I know this is just for better readability.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/3663215/c-sharp-stylecop-using-this-prefix-for-base-class-members-like-current-clas

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