我有一个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
。我有点困惑,我怎么才能让它正常工作?非常感谢帮助。
您应该将缓存定义为'IDictionary(Of C,T)'否则它将是无类型的,即它将返回对象。 –