VB.NET中的静态成员 [英] Static members in VB.NET

查看:167
本文介绍了VB.NET中的静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前是这样写的:

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

问题是,"New"位仅在第一次执行该功能时执行一次,但是在下一次调用中它将已经存在.

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.

干杯,罗布.

推荐答案

它只会执行一次,并且在下一次函数调用时,它将引用您提到的同一对象.顺便说一句,您的第一个代码段不是线程安全的.如果两个线程同时调用您的函数,则它们可能最终两次运行构造函数,而这不是您想要的.使用第二个代码段可以避免您手动锁定并确保线程安全,因为编译器会为您生成适当的代码.

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)

每次都会重新创建.

这篇关于VB.NET中的静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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