2016-12-30 71 views
0

如果我在VB.NET使用這種形狀的屬性得到:VB.NET屬性獲取和緩存

Public ReadOnly Property Thing(i as long) as double(,) 
    Get 
     Return SomeCalculation(i) 
    End Get 
End Property 

和調用的代碼與同我許多倍的性能獲得(做後與另一個iscen相同,等等),結果將被緩存,直到我使用新的i或將每次重新計算嗎?

謝謝!

+2

每次都會重新計算。沒有自動提供緩存。 – Steve

+0

屬性只是語法糖,並被實現爲一個或一對方法。方法結果不會隱式緩存。我想說,這可能不應該是一個財產,而應該是一種方法,在這種情況下,不會出現混淆。 – jmcilhinney

+0

感謝這兩個。你會把它作爲答案,所以問題被標記爲回答? – Pierre

回答

1

不,VB.NET中沒有自動緩存來存儲重複計算的結果。您需要提供某種緩存。

例如,你可以使用字典

Dim cache As Dictionary(Of Long, Double(,)) = New Dictionary(Of Long, Double(,)) 

Public ReadOnly Property Thing(i as long) as double(,) 
    Get 
     Dim result As Double(,) 
     If Not cache.TryGetValue(i, result) Then 
      result = SomeCalculation(i) 
      cache.Add(i, result) 
     End If 
     Return result 
    End Get 
End Property 

當然,任何簡單的解決方案,也有一些需要考慮的要點:

  • 沒有失效規則(緩存仍然是積極的應用程序的生命週期 )
  • 它假定計算總是產生相同的結果 相同的輸入
+0

還可以考慮使用'懶惰'。 –

+0

@CodyGray有趣。我不習慣它。你能提供一個例子嗎? – Steve

+1

聲明一個類型爲'Lazy '的私有備份變量,然後創建一個公共屬性,該屬性返回'Lazy '變量的'Value'成員。看,例如:http://stackoverflow.com/a/2579378/366904和http://stackoverflow.com/questions/5134786/cached-property-vs-lazyt –

1

您可以爲緩存值

Public Class LongCaches(Of MyType) 
    Protected MyDictionary Dictionary(Of Long, MyType) = New Dictionary(Of Long, MyType) 
    Public Delegate Function MyFunction(Of Long) As MyType 
    Protected MyDelegate As MyFunction 
    Public Calculate As Function(ByVal input As Long) As MyType 
     If Not MyDictionary.ContainsKey(input) Then 
      MyDictionary(input) = MyFunction.Invoke(input) 
     End If 
     Return MyDictionary(input) 
    End Function 
    Public Sub New(ByVal myfunc As MyFunction) 
     MyDelegate = myfunc 
    End Sub 
End Caches 

您將需要使用像這樣創建一個類:

Private _MyLongCacheProperty As LongCaches(Of Double(,)) 
Protected ReadOnly MyLongCacheProperty(i As Long) As LongCaches 
Get 
    If _MyLongCacheProperty Is Nothing Then 
     _MyLongCacheProperty = New LongCaches(Of Double(,))(AddressOf SomeCalculation) 
    End If 
    Return _MyLongCacheProperty.Calculate(i) 
End Get 
End Property 

聲明:此代碼是未經測試,如果有語法錯誤,那麼請評論或編輯而不是downvote。