这不是线程安全的,但非常适合我的目的:
使用中的解决方案:
Private _formattedFormulaText As New Lazy(Of IEnumerable(Of Label))(Function() New List(Of Label) From { _
FormulaLabels0, FormulaLabels1, lblBrownFormula, FormulaLabels3, lblGreenFormula, _
lblOrangeFormula, lblSRedFormula, FormulaLabels7, lblFormulaTotal})
缺点- 所有涉及变量的代码都必须添加访问器.value
。我的代码有 5 个这样的惰性集合,每个集合有 1-2 个接触点,通常在同一个函数中。
缺点说明:
Dim clearText = Sub(c As Control) c.Text = String.Empty
_formattedFormulaText.ToList.ForEach(clearText)
变成
Dim clearText = Sub(c As Control) c.Text = String.Empty
_formattedFormulaText.Value.ToList.ForEach(clearText)
不符合 .net 4 中使用的调试器显示的良好做法,但使用反射器很容易添加
请注意,可以使用属性来消除接触点中 .value 的需要:
Private ReadOnly Property FormattedText As IEnumerable(Of Label)
Get
Return _formattedFormulaText.Value
End Get
End Property
支持类:
''' <summary>
''' translated from http://msdn.microsoft.com/en-us/vcsharp/bb870976.aspx
''' </summary>
Public Class Lazy(Of T)
Private _func As Func(Of T)
Private _result As T
Private _hasValue As Boolean
Public Sub New(ByVal func As Func(Of T))
_func = func
_hasValue = False
End Sub
Public ReadOnly Property Value As T
Get
If Me._hasValue = False Then
_result = _func()
_hasValue = True
End If
Return _result
End Get
End Property
End Class
设计基于 MSDN 的文章Lazy Computation in C#
也借助 Reflector 针对
assembly\NativeImages_v4.0.30319_32\mscorlib\246f1a5abb686b9dcdf22d3505b08cea\mscorlib.ni.dll