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.
在我看来,性能、名称空间污染等都是次要的。问问自己什么是合乎逻辑的。该方法在逻辑上操作类型的实例,还是与类型本身相关?如果是后者,则将其设置为静态方法。只有当它与不受您控制的类型相关时,才将其移动到实用程序类中。
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.)
静态方法与实例方法 c#语言规范的静态成员和实例成员解释了这种差异。一般来说,静态方法可以提供比实例方法非常小的性能增强,但仅在某些极端情况下(有关详细信息,请参阅此回答)。
FxCop或代码分析中的CA1822规则规定:
在[将成员标记为静态]之后,编译器将向这些成员发出非虚拟调用站点,这将防止在 运行时,确保当前对象指针为 非空。这可以导致可测量的性能增益 性能敏感的代码。在某些情况下,访问失败 当前对象实例表示正确性问题。”
实用程序类 除非在设计中有意义,否则不应该将它们移到实用程序类中。如果静态方法与特定类型有关,就像ToRadians(双度)方法与表示角度的类有关一样,那么该方法作为该类型的静态成员存在是有意义的(注意,为了演示,这是一个复杂的示例)。
读起来很有趣: http://thecuttingledge.com/?p=57
ReSharper实际上并不是建议您将方法设置为静态的。 你应该问问自己,为什么这个方法在那个类中,而不是在它的签名中出现的类之一…
但ReSharper documentaion是这么说的: http://confluence.jetbrains.net/display/ReSharper/Member+can+be+made+static
只是我的一点钱:将所有共享的静态方法添加到实用程序类中,您就可以添加
using static className;
到您的using语句,这使得代码更快地输入和更容易阅读。例如,我在继承的一些代码中有大量所谓的“全局变量”。我没有在一个属于实例类的类中创建全局变量,而是将它们全部设置为全局类的静态属性。它完成了这项工作,虽然有些混乱,但我可以按名称引用属性,因为我已经引用了静态名称空间。
我不知道这是不是一个好的练习。关于c# 4/5,我有很多东西要学,还有很多遗留代码要重构,所以我只是想让Roselyn的技巧来指导我。
Joey