.net IDictionary.Item返回错误的类型
我对IDictionary.Item返回类型有问题。代码如下:.net IDictionary.Item返回错误的类型,.net,vb.net,.net,Vb.net,我对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
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
Class SomeClass实现了(C的)IComparer
私有只读缓存作为IDictionary=新字典(属于C,T)
公共函数compare(ByVal chr1作为C,ByVal chr2作为C)作为整数实现IComparer(属于C)。compare
尺寸配合1作为T=Me.fit(chr1)
尺寸配合2作为T=Me.fit(chr2)
Dim ret As Integer=fit1。比较到(fit2)
回程网
端函数
公共可重写函数fit(ByVal chr As C)As T
Dim适合于T=Me.cache.Item(chr)double是一种“值类型”(而不是常见的“引用类型”)。这意味着它不可能是空的,当您期望它是空的时候,它实际上将是它的默认值(double中的0.0)
这同样适用于所有基本类型(int、long、char…)和结构类型。如果字典包含的值类型或引用类型为Nothing
或可为null的类型为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
,如果可用,则返回找到的项。您应该将缓存定义为IDictionary(of C,T)
,否则它将是非类型化的,即它将返回对象。