简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM