如果说* *可以是静态的C#方法是静态的? [英] Should C# methods that *can* be static be static?

查看:80
本文介绍了如果说* *可以是静态的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. 方法,因为它们有一个是静态为

在一个小到中等规模的code碱基你真的可以治疗两种方法交替。

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.

在一个大code基,但是,调用点数量之多可能使搜索,看是否有可能一个静态方法转换为非静态的成本太高。很多时候,人们会看到调用的次数,并说:好吧......我最好不要改变这种方法,而是创建做什么,我需要一个新的。

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. 很多code重复

  2. 在方法参数数量的爆炸

这两点都是不好的。

所以,我的建议是,如果你有一个code基超过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.

从非静态静态重构是比较容易的(只需添加一个关键字),所以如果你想使(实例之外,当你需要它的功能),一个可以成为的静态成实际的静态以后再您可以。然而,逆重构,转动可待静态成实例方法昂贵得多。

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.

使用大code碱基最好是在易于扩展的端的错误,而不是思想体系纯洁的一面。

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天全站免登陆