代码之家  ›  专栏  ›  技术社区  ›  Amir Karimi

C#StyleCop-是否为基类成员使用“this.”前缀,比如当前类成员?

  •  8
  • Amir Karimi  · 技术社区  · 16 年前

    StyleCop有一个关于使用“this.”前缀调用类成员的规则(SA1101)。

    对于从基类继承的类的成员(例如方法),此规则是否成立。

    例子:

    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?
        }
    }
    

    我知道这只是为了更好的可读性。

    4 回复  |  直到 16 年前
        1
  •  6
  •   Timwi    16 年前

    这个 documentation for StyleCop Rule SA1101 实际上提到了这一点:

    本地类或基类的

    (我自己强调)。是的,规则要求 this. 每次访问实例成员时,不管该成员是在本地类中还是从基类继承的。

        2
  •  5
  •   Scott Dorman    16 年前

    如果你考虑一下对象继承的规则 F1() 实际上是在 BaseClass 它是由 ChildClass this.F1() . 这就是StyleCop要你做的。在通话前加上 this F1() 实例 类的当前运行时实例的。

    实际上是同义词,但使用 前缀。

    base 前缀在这里(即使它会编译),因为 不是虚拟的,正在中重写 儿童班 基础 基础 F1() 在你做出决定之前 F1() 虚拟并在中添加了重写 . 到那时,有人打电话给我吗 base.F1() BaseClass.F1() 而不是新的超驰控制 .

        3
  •  0
  •   Nathan    16 年前

        4
  •  -3
  •   jwetzel1492    16 年前

    我喜欢用碱。base.F1()用于您的案例。它可以防止意外引用局部变量,并直观地提醒成员来自何处。