在Visual Studio / C#中编译时强制使用“this”和“base”

时间:2023-01-16 15:53:09

When extending classes, I find it very descriptive to use the base (MyBase in VB) keyword when accessing methods in the base-class. And the this (Me in VB) keyword when accessing functions in the class extending the base-class. That goes for a "flat" structure with no inheritance as well.

在扩展类时,我发现在访问基类中的方法时使用base(MyBase in VB)关键字非常具有描述性。当在扩展基类的类中访问函数时,这个(Me in VB)关键字。这适用于没有继承的“扁平”结构。

I find it easier to read this:

我觉得这更容易理解:

public class World
{
    public String baseName = "World";
}


public class Hello : World
{
    public String thisName = "Hello";


    public String GetNames()
    {
        return this.thisName + " " + base.baseName;
    }
}

Than this:

...

    public String GetNames()
    {
        return thisName + " " + baseName;
    }

...

Now, my question is: is it possible to enforce the use of this and base at compile-time in Visual Studio/C#, so that the compiler throws an error or a warning if you do not use these keywords in your code?

现在,我的问题是:是否可以在Visual Studio / C#中在编译时强制使用this和base,以便在代码中不使用这些关键字时,编译器会抛出错误或警告?

2 个解决方案

#1


4  

Have a look at StyleCop.

看看StyleCop。

http://code.msdn.microsoft.com/sourceanalysis

There are some rules in there that should do what you want. You can configure it to show any style violations as warnings or errors.

那里有一些规则应该做你想要的。您可以将其配置为将任何样式违规显示为警告或错误。

#2


0  

You may also want to check out SSW's code auditor

您可能还想查看SSW的代码审核员

Unfortunately there is no way that I'm aware of to enforce this in the compiler.

不幸的是,我无法在编译器中强制执行此操作。

#1


4  

Have a look at StyleCop.

看看StyleCop。

http://code.msdn.microsoft.com/sourceanalysis

There are some rules in there that should do what you want. You can configure it to show any style violations as warnings or errors.

那里有一些规则应该做你想要的。您可以将其配置为将任何样式违规显示为警告或错误。

#2


0  

You may also want to check out SSW's code auditor

您可能还想查看SSW的代码审核员

Unfortunately there is no way that I'm aware of to enforce this in the compiler.

不幸的是,我无法在编译器中强制执行此操作。