*可以*是静态的C#方法应该是静态的吗? [英] Should C# methods that *can* be static be static?

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

问题描述

可以静态的 C# 方法应该是静态的吗?

Should C# methods that can be static be static?

我们今天讨论了这个问题,我有点犹豫.想象一下,您有一个很长的方法,您可以从中重构几行.新方法可能从父方法中获取一些局部变量并返回一个值.这意味着它可以是静态的.

We were discussing this today and I'm kind of on the fence. Imagine you have a long method that you refactor a few lines out of. The new method probably takes a few local variables from the parent method and returns a value. This means it could be static.

问题是:应该它是静态的吗?它不是静态的设计或选择,只是因为它不引用任何实例值的性质.

The question is: should it be static? It's not static by design or choice, simply by its nature in that it doesn't reference any instance values.

推荐答案

视情况而定.实际上有两种类型的静态方法:

It depends. There are really 2 types of static methods:

  1. 静态方法,因为它们可以
  2. 静态方法,因为它们必须是

在中小型代码库中,您真的可以互换使用这两种方法.

In a small to medium size code base you can really treat the two methods interchangeably.

如果您有一个属于第一类(可以是静态的)的方法,并且您需要将其更改为访问类状态,那么确定是否可以将静态方法转换为一个相对简单的方法实例方法.

If you have a method that is in the first category (can-be-static), and you need to change it to access class state, it's relatively straight forward to figure out if it's possible to turn the static method into a instance method.

然而,在大型代码库中,调用站点的绝对数量可能会使搜索以查看是否有可能将静态方法转换为非静态方法的成本太高.很多时候人们会看到调用次数,然后说好吧……我最好不要改变这个方法,而是创建一个满足我需要的新方法".

In a large code base, however, the sheer number of call sites might make searching to see if it's possible to convert a static method to a non static one too costly. Many times people will see the number of calls, and say "ok... I better not change this method, but instead create a new one that does what I need".

这可能导致:

  1. 大量代码重复
  2. 方法参数数量激增

这两件事都很糟糕.

因此,我的建议是,如果您的代码库超过 200K LOC,那么我只会将必须是静态方法的方法设为静态.

So, my advice would be that if you have a code base over 200K LOC, that I would only make methods static if they are must-be-static methods.

从非静态到静态的重构相对容易(只需添加一个关键字),因此如果您想稍后将 can-be-static 变成实际的静态(当您需要它在实例之外的功能时)那么你可以.然而,逆重构,将一个可以是静态的方法变成一个实例方法,成本要高得多.

The refactoring from non-static to static is relatively easy (just add a keyword), so if you want to make a can-be-static into an actual static later (when you need it's functionality outside of an instance) then you can. However, the inverse refactoring, turning a can-be-static into a instance method is MUCH more expensive.

对于大型代码库,最好在易于扩展的方面出错,而不是在理想的纯洁性方面.

With large code bases it's better to error on the side of ease of extension, rather than on the side of idealogical purity.

因此,对于大型项目,除非您需要,否则不要让事情变得静态.对于小项目,只做你最喜欢的事情.

So, for big projects don't make things static unless you need them to be. For small projects, just do what ever you like best.

这篇关于*可以*是静态的C#方法应该是静态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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