2013-12-07 42 views
0

我有一個IDictionary.Item返回類型的問題。以下是代碼:IDictionary.Item返回錯誤的類型

Class SomeClass Implements IComparer(Of C) 

Private ReadOnly cache As IDictionary = New Dictionary(Of C, T) 

Public Function compare(ByVal chr1 As C, ByVal chr2 As C) As Integer Implements IComparer(Of C).Compare 
       Dim fit1 As T = Me.fit(chr1) 
       Dim fit2 As T = Me.fit(chr2) 
       Dim ret As Integer = fit1.CompareTo(fit2) 
       Return ret 
      End Function 

Public Overridable Function fit(ByVal chr As C) As T 
       Dim fits As T = Me.cache.Item(chr) '<----- Here it fails 
       If fits Is Nothing Then '<------ False, because fits == 0.0 
        fits = fitnessFunc.calculate(chr) 
        Me.cache.Add(chr, fits) 
       End If 
       Return fits 
      End Function 
End Class 

我的cache爲空。 MSDN表示IDictionary.Item返回帶有指定鍵的元素,如果該鍵不存在,則返回Nothing。但是,我的fits類型爲Double,並且由於未知原因,它等於0.0,但它必須是Nothing。我有點困惑,我怎麼才能讓它正常工作?非常感謝幫助。

+0

您應該將緩存定義爲'IDictionary(Of C,T)'否則它將是無類型的,即它將返回對象。 –

回答

0

如果字典包含值類型,或者是Nothing或可空類型是Nothing甚至引用類型,IDictionary.Item有沒有告訴你的項目是否在高速緩存中找到或只是類型的默認值是否被退回,因爲方式鍵未找到。

更好地運用字典的TryGetValue方法:

Dim fits As T 
If cache.TryGetValue(chr, fits) Then 
    ' We found an item in the cache 
Else 
    ' We must calculate the missing item and add it to the cache 
End If 

注:TryGetValue第二個參數是ByRef,如果可用返回找到的項目。

0

double是一個「值類型」(而不是常見的「引用類型」)。這意味着它不能是Nothing,並且當你期望它是Nothing時,它實際上就是它的默認值(它是0.0的兩倍)。

對於所有基元類型(int,long,char ...)和結構類型也是如此。