Static members in VB.NET

眉间皱痕 提交于 2020-01-03 15:53:05

问题


I used to write this:

Private Sub Example()
Static CachedPeople As List(Of MyApp.Person)
If CachedPeople Is Nothing Then
    CachedPeople = New List(Of MyApp.Person)
End If
...rest of code...
End Sub

But then wondered if I could reduce this to:

Private Sub Example()
Static CachedPeople As New List(Of MyApp.Person)
...rest of code...
End Sub

The question is, will the "New" bit only be executed once when the function is first executed but in the next call, it will already exist.

Cheers, Rob.


回答1:


It'll be executed only once and on next function call, it'll reference the same object, as you mentioned. Your first snippet is not thread-safe, by the way. If two threads call your function at the same time, they might end up running the constructor twice, which is not what you want. Using the second snippet relieves you from manually locking and ensuring thread safety, as the compiler generates the appropriate code for you.

Note that if you had declared it as

Static x As List(Of String)
x = New List(Of String)

It would have been recreated each time.



来源:https://stackoverflow.com/questions/1483760/static-members-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!