ReSharper喜欢在每个ASP中指出多个函数。NET页面,可以设置为静态。如果我把它们变成静态的,对我有帮助吗?我是否应该将它们设置为静态并将它们移动到实用程序类中?


当前回答

Just to add to @Jason True's answer, it is important to realise that just putting 'static' on a method doesn't guarantee that the method will be 'pure'. It will be stateless with regard to the class in which it is declared, but it may well access other 'static' objects which have state (application configuration etc.), this may not always be a bad thing, but one of the reasons that I personally tend to prefer static methods when I can is that if they are pure, you can test and reason about them in isolation, without having to worry about the surrounding state.

其他回答

Just to add to @Jason True's answer, it is important to realise that just putting 'static' on a method doesn't guarantee that the method will be 'pure'. It will be stateless with regard to the class in which it is declared, but it may well access other 'static' objects which have state (application configuration etc.), this may not always be a bad thing, but one of the reasons that I personally tend to prefer static methods when I can is that if they are pure, you can test and reason about them in isolation, without having to worry about the surrounding state.

如果函数在许多页面中共享,你也可以把它们放在一个基页类中,然后让所有使用该功能的asp.net页面继承它(函数也可以仍然是静态的)。

静态方法与实例方法 c#语言规范的静态成员和实例成员解释了这种差异。一般来说,静态方法可以提供比实例方法非常小的性能增强,但仅在某些极端情况下(有关详细信息,请参阅此回答)。

FxCop或代码分析中的CA1822规则规定:

在[将成员标记为静态]之后,编译器将向这些成员发出非虚拟调用站点,这将防止在 运行时,确保当前对象指针为 非空。这可以导致可测量的性能增益 性能敏感的代码。在某些情况下,访问失败 当前对象实例表示正确性问题。”

实用程序类 除非在设计中有意义,否则不应该将它们移到实用程序类中。如果静态方法与特定类型有关,就像ToRadians(双度)方法与表示角度的类有关一样,那么该方法作为该类型的静态成员存在是有意义的(注意,为了演示,这是一个复杂的示例)。

我相信这不会发生在您的情况下,但是在我不得不忍受维护的一些代码中,我看到了使用大量静态方法的“坏味道”。

不幸的是,它们是假定特定应用程序状态的静态方法。(当然,每个应用程序只有一个用户!为什么不让User类在静态变量中跟踪它呢?)它们是访问全局变量的光荣方法。它们还有静态构造函数(!),这几乎总是一个坏主意。(我知道有一些合理的例外)。

然而,静态方法在排除域逻辑(实际上不依赖于对象实例的状态)时非常有用。它们可以使您的代码更具可读性。

只要确保你把它们放在正确的地方。静态方法是否侵入式地操纵其他对象的内部状态?能不能证明他们的行为属于其中一类呢?如果你没有正确地分离问题,你以后可能会头疼。

对于类中的复杂逻辑,我发现私有静态方法在创建隔离逻辑时很有用,其中实例输入在方法签名中明确定义,并且不会发生实例副作用。所有输出必须通过返回值或out/ref参数。将复杂的逻辑分解成无副作用的代码块可以提高代码的可读性和开发团队对它的信心。

另一方面,它可能导致类被大量实用方法所污染。通常,逻辑命名、文档和团队编码约定的一致应用程序可以缓解这种情况。