2013-12-07 43 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 ...)和结构类型也是如此。