静态在VB中意味着什么?

时间:2010-02-21 09:18:37

标签: vb.net

静态在VB中意味着什么?

编辑 - 代码示例供参考

Module Module1

    Sub Main()
        Dim a = New Foo
        Dim b = New Foo
        Console.WriteLine(a.Boom)
        Console.WriteLine(a.Boom)
        Console.WriteLine(a.Boom)
        Console.WriteLine(b.Boom)
    End Sub

End Module


Class Foo
    Function Boom() As Integer
        Static callCount As Integer = 0
        callCount += 1
        Return callCount
    End Function
End Class

1 个答案:

答案 0 :(得分:4)

这是一种拥有方法本地字段的方法。基本上,值在调用之间保持不变,但在类的其他部分中不可访问。有关实施信息,请参阅Static Local Variables in VB.NET

编辑:Jonathan,你说这些字段不必是共享/静态是正确的。如果函数/ sub声明为Shared,则它将是Shared / static字段。否则,它将是一个实例字段。无论哪种方式,它都是持久的调用和本地方法。以下示例(继续a theme)清楚地显示了这两种行为:

Class Fibonacci

    Public Function FibonacciInstance() as Integer
           Static i as Integer = -1
           Static j as Integer = 1
           Dim k as Integer

           k = i + j
           i = j
           j = k

           return k
    End Function

    Public Shared Function FibonacciShared() as Integer
           Static i as Integer = -1
           Static j as Integer = 1
           Dim k as Integer

           k = i + j
           i = j
           j = k

           return k
    End Function

    Shared Sub Main()
        Dim d as Integer
        Dim a = New Fibonacci
        Dim b = New Fibonacci       
        For d = 0 to 10
            System.Console.WriteLine("a.FibonacciInstance: " & a.FibonacciInstance())
            System.Console.WriteLine("b.FibonacciInstance: " & b.FibonacciInstance())
            System.Console.WriteLine("a.FibonacciShared: " & a.FibonacciShared())
            System.Console.WriteLine("b.FibonacciShared: " & b.FibonacciShared())
        Next d
    End Sub

End Class