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


当前回答

只是我的一点钱:将所有共享的静态方法添加到实用程序类中,您就可以添加

using static className; 

到您的using语句,这使得代码更快地输入和更容易阅读。例如,我在继承的一些代码中有大量所谓的“全局变量”。我没有在一个属于实例类的类中创建全局变量,而是将它们全部设置为全局类的静态属性。它完成了这项工作,虽然有些混乱,但我可以按名称引用属性,因为我已经引用了静态名称空间。

我不知道这是不是一个好的练习。关于c# 4/5,我有很多东西要学,还有很多遗留代码要重构,所以我只是想让Roselyn的技巧来指导我。

Joey

其他回答

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.

使方法静态意味着您可以从类外部调用该方法,而无需首先创建该类的实例。这在使用第三方供应商对象或附加组件时非常有用。想象一下,如果你在调用con. writeline()之前必须先创建一个Console对象“con”;

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

我希望您已经理解了静态方法和实例方法之间的区别。而且,答案可以有长有短。其他人已经给出了很长的答案。

我的简短回答是:是的,你可以像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.

ReSharper不检查逻辑。它只检查方法是否使用实例成员。 如果方法是私有的,并且只被(可能只有一个)实例方法调用,这是一个让它成为实例方法的标志。