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.
使方法静态意味着您可以从类外部调用该方法,而无需首先创建该类的实例。这在使用第三方供应商对象或附加组件时非常有用。想象一下,如果你在调用con. writeline()之前必须先创建一个Console对象“con”;
您应该在给定的场景中使用最易读和最直观的方法。
除了在最极端的情况下,性能参数并不是一个好的参数,因为实际发生的唯一事情是将一个额外的参数(this)推入到实例方法的堆栈中。
在类中将方法标记为静态可以明显地表明它不使用任何实例成员,这有助于在浏览代码时了解这一点。
你不一定要把它移到另一个类中,除非它被另一个在概念上紧密关联的类所共享。
在我看来,性能、名称空间污染等都是次要的。问问自己什么是合乎逻辑的。该方法在逻辑上操作类型的实例,还是与类型本身相关?如果是后者,则将其设置为静态方法。只有当它与不受您控制的类型相关时,才将其移动到实用程序类中。
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.)
推荐文章
- 在EF中更新父实体时如何添加/更新子实体
- ASP。NET身份的默认密码散列器-它是如何工作的,它是安全的?
- 如何写一个JSON文件在c# ?
- 静态隐式运算符
- 不区分大小写列表搜索
- 'throw'和'throw new Exception()'的区别
- 不能在lambda表达式中使用ref或out参数
- c# int到字节[]
- 如何跟踪log4net问题
- 将WPF组合框绑定到自定义列表
- foreach vs somlist . foreach (){}
- 为什么try{…}最后{…}好;尝试{…} catch{}坏?
- c# 8用多种情况切换表达式,结果相同
- 在没有事件源注册的情况下写入Windows应用程序事件日志
- 并发HashSet<T>在。net框架?