方法可静态的,而应该吗? [英] Method can be made static, but should it?

查看:108
本文介绍了方法可静态的,而应该吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

静态方法与实例方法
10.2.5静态和实例成员中的C#语言规范的解释差分。一般来说,静态方法可以提供一个非常小的性能提升(更不用说节省内存根据实例类可能希望创建数)以上的实例方法,但只是在有些极端的情况下。

Static methods versus Instance methods
10.2.5 Static and instance members of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement (not to mention a memory saving depending on the number of instances your class might expect to create) over instance methods, but only in somewhat extreme situations.

在的FxCop规则CA1822或code分析指出:

Rule CA1822 in FxCop or Code Analysis states:

后[标记成员静态],编译器将发出非虚拟调用点到这些成员将prevent一张支票   运行时每个调用,以确保当前对象的指针   非空。这会导致可观的性能增益   性能敏感的code。在某些情况下,失败访问   再$ P $当前对象实例psents一个正确的问题。

"After [marking members as static], the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that ensures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."

工具类
你不应该将它们移到一个实用程序类,除非它是有道理的在您的设计。如果静态方法涉及到一个特定的类型,像一个ToRadians(双学位)方法涉及一类重presenting的角度,这是有道理的,该方法存在作为该类型(注:静态成员,这是一个令人费解的例子演示的目的)。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆