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.

其他回答

您应该在给定的场景中使用最易读和最直观的方法。

除了在最极端的情况下,性能参数并不是一个好的参数,因为实际发生的唯一事情是将一个额外的参数(this)推入到实例方法的堆栈中。

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

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

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

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

在类中将方法标记为静态可以明显地表明它不使用任何实例成员,这有助于在浏览代码时了解这一点。

你不一定要把它移到另一个类中,除非它被另一个在概念上紧密关联的类所共享。

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.

它有助于控制名称空间污染。