静态局部变量是不好的做法吗? [英] Are static local variables bad practice?
问题描述
相关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屋!