方法可以静态化,但应该这样吗? [英] Method can be made static, but should it?
问题描述
ReSharper 喜欢指出每个 ASP.NET 页面的多个可以设为静态的功能.如果我确实让它们静态,它对我有帮助吗?我应该将它们设为静态并将它们移至实用程序类吗?
ReSharper likes to point out multiple functions per ASP.NET page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class?
推荐答案
静态方法与实例方法
静态和实例C# 语言规范的成员 解释了差异.通常,静态方法相对于实例方法可以提供非常小的性能增强,但仅限于在某些极端情况下(参见 this answer一些更多的细节).
Static methods versus Instance methods
Static and instance members of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement over instance methods, but only in somewhat extreme situations (see this answer for some more details on that).
FxCop 或代码分析状态中的 CA1822 规则:
Rule CA1822 in FxCop or Code Analysis states:
"在[将成员标记为静态]之后,编译器将向这些成员发出非虚拟调用站点,这将阻止检查确保当前对象指针为每个调用的运行时非空.这可能会导致可衡量的性能提升对性能敏感的代码.在某些情况下,无法访问当前对象实例表示正确性问题."
实用程序类
除非在您的设计中有意义,否则您不应将它们移至实用程序类.如果静态方法与特定类型相关,例如 ToRadians(double degree)
方法与表示角度的类相关,则该方法作为该类型的静态成员存在是有意义的(注意,这是一个用于演示目的的复杂示例).
Utility Class
You shouldn't move them to a utility class unless it makes sense in your design. If the static method relates to a particular type, like a ToRadians(double degrees)
method relates to a class representing angles, it makes sense for that method to exist as a static member of that type (note, this is a convoluted example for the purposes of demonstration).
这篇关于方法可以静态化,但应该这样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!