静态局部变量是不好的做法吗? [英] Are static local variables bad practice?

查看:126
本文介绍了静态局部变量是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关C ++问题:方法中的静态局部变量是不好的做法?

在VB.NET中,当我想要一个简单的计数器或每次调用一个方法时增加的事情,我经常发现自己编写的代码如下: / p>

In VB.NET, when I want a simple counter or something that increments each time a method is called, I often find myself writing code like:

Private Sub tmrRefresh_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrRefresh.Tick

  Static a As Integer = 0
  a += 1
  '...rest of method depends on a

End Sub

这是建议在VB.NET和OOP一般吗?

Is this recommended in VB.NET and OOP in general?

推荐答案


是静态局部变量不好的做法吗?

Are static local variables bad practice?

。静态局部变量在一定程度上与非本地私有变量有所不同:它们的范围较小。由于您始终希望尽可能小的范围(=更好的封装),本地静态可能比私有变量更有利。

No. Static local variables differ in exactly one regard to non-local private variables: they have a smaller scope. Since you always want to keep scope as small as possible (= better encapsulation), local statics can be advantageous over private variables.

另外,本地静态变量可能很难正确初始化。如果需要复杂的初始化(例如,如果您需要稍后重新初始化变量),则本地静态变量可能不适用。

On the flip-side, local static variables may be hard to initialise correctly. If a complex initialisation is required (for example, if you need to re-initialise a variable later on), local static variables may be unsuitable.

这篇关于静态局部变量是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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