ReSharper喜欢在每个ASP中指出多个函数。NET页面,可以设置为静态。如果我把它们变成静态的,对我有帮助吗?我是否应该将它们设置为静态并将它们移动到实用程序类中?
当前回答
在我看来,性能、名称空间污染等都是次要的。问问自己什么是合乎逻辑的。该方法在逻辑上操作类型的实例,还是与类型本身相关?如果是后者,则将其设置为静态方法。只有当它与不受您控制的类型相关时,才将其移动到实用程序类中。
Sometimes there are methods which logically act on an instance but don't happen to use any of the instance's state yet. For instance, if you were building a file system and you'd got the concept of a directory, but you hadn't implemented it yet, you could write a property returning the kind of the file system object, and it would always be just "file" - but it's logically related to the instance, and so should be an instance method. This is also important if you want to make the method virtual - your particular implementation may need no state, but derived classes might. (For instance, asking a collection whether or not it's read-only - you may not have implemented a read-only form of that collection yet, but it's clearly a property of the collection itself, not the type.)
其他回答
我希望您已经理解了静态方法和实例方法之间的区别。而且,答案可以有长有短。其他人已经给出了很长的答案。
我的简短回答是:是的,你可以像ReSharper建议的那样将它们转换为静态方法。这样做没有坏处。相反,通过将方法设置为静态,实际上是在保护该方法,这样就不会不必要地将任何实例成员插入该方法。通过这种方式,您可以实现OOP原则“最小化类和成员的可访问性”。
When ReSharper is suggesting that an instance method can be converted to a static one, it is actually telling you, "Why the .. this method is sitting in this class but it is not actually using any of its states?" So, it gives you food for thought. Then, it is you who can realize the need for moving that method to a static utility class or not. According to the SOLID principles, a class should have only one core responsibility. So, you can do a better cleanup of your classes in that way. Sometimes, you do need some helper methods even in your instance class. If that is the case, you may keep them within a #region helper.
在类中将方法标记为静态可以明显地表明它不使用任何实例成员,这有助于在浏览代码时了解这一点。
你不一定要把它移到另一个类中,除非它被另一个在概念上紧密关联的类所共享。
我相信这不会发生在您的情况下,但是在我不得不忍受维护的一些代码中,我看到了使用大量静态方法的“坏味道”。
不幸的是,它们是假定特定应用程序状态的静态方法。(当然,每个应用程序只有一个用户!为什么不让User类在静态变量中跟踪它呢?)它们是访问全局变量的光荣方法。它们还有静态构造函数(!),这几乎总是一个坏主意。(我知道有一些合理的例外)。
然而,静态方法在排除域逻辑(实际上不依赖于对象实例的状态)时非常有用。它们可以使您的代码更具可读性。
只要确保你把它们放在正确的地方。静态方法是否侵入式地操纵其他对象的内部状态?能不能证明他们的行为属于其中一类呢?如果你没有正确地分离问题,你以后可能会头疼。
读起来很有趣: http://thecuttingledge.com/?p=57
ReSharper实际上并不是建议您将方法设置为静态的。 你应该问问自己,为什么这个方法在那个类中,而不是在它的签名中出现的类之一…
但ReSharper documentaion是这么说的: http://confluence.jetbrains.net/display/ReSharper/Member+can+be+made+static
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.