2010-02-21 71 views
1

在VB中靜態意味着什麼?靜態在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 

回答

4

它是具有本地的方法領域的一種方式。基本上,價值在呼叫之間保持,但在班級的其他部分無法訪問。有關實施信息,請參見Static Local Variables in VB.NET

編輯:喬納森,你是對的,領域不必共享/靜態。如果函數/子被聲明爲共享,它將是一個共享/靜態字段。否則,它將是一個實例字段。無論哪種方式,它在呼叫中持續存在,而且在方法本地持續存在。下面的例子(繼續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 
+0

+1但請提供代碼示例。 – Dario 2010-02-21 09:20:40

+0

沒有。我剛剛檢查過,它絕對不像共享字段。如果我在編輯的問題中運行代碼,我會得到「1,2,3,1」。 – 2010-02-21 09:27:58