请您查看下面的代码,注意返回错误消息的3个位置并建议修复?注释掉的错误位于违规行的右侧
谢谢!
Public Interface IIdentity
Property Identity As Integer
End Interface
Public Class IdentityCollection(Of T As IIdentity)
'Inherits System.Collections.ObjectModel.Collection(Of T)
Inherits System.Collections.Generic.Dictionary(Of Integer, T)
Public Function ItemByPrimaryKey(identity As Integer) As T
For Each currentItem As T In Me 'Error 1 Value of type 'System.Collections.Generic.KeyValuePair(Of Integer, T)' cannot be converted to 'T'. d:\users\chad\documents\visual studio 2010\Projects\WindowsApplication4\WindowsApplication4\Class2.vb 18 38 WindowsApplication4
If currentItem.Key = identity Then 'Error 2 'Key' is not a member of 'T'. d:\users\chad\documents\visual studio 2010\Projects\WindowsApplication4\WindowsApplication4\Class2.vb 19 16 WindowsApplication4
Return T
End If
Next
Return Nothing
End Function
Public Function ItemByPrimaryKeySecondApproach(identity As Integer) As T
Return (From X In Me Select X Where X.Key = identity).FirstOrDefault 'Error 4 Value of type 'System.Collections.Generic.KeyValuePair(Of Integer, T)' cannot be converted to 'T'. d:\users\chad\documents\visual studio 2010\Projects\WindowsApplication4\WindowsApplication4\Class2.vb 27 16 WindowsApplication4
End Function
Public Shadows Sub Add(item As T)
MyBase.Add(item.Identity, item)
End Sub
End Class
Public Class Customer
Implements IIdentity
Public Sub New(customerKey As Integer, lastName As String, firstname As String)
_CustomerKey = customerKey
_LastName = lastName
_FirstName = firstname
End Sub
Private _CustomerKey As Integer
Public Property CustomerKey As Integer Implements IIdentity.Identity
Get
Return _CustomerKey
End Get
Set(value As Integer)
_CustomerKey = value
End Set
End Property
Private _LastName As String
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
Private _FirstName As String
Public Property FirstName() As String
Get
Return _FirstName
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
End Class
Public Class CustomerCollection
Inherits IdentityCollection(Of Customer)
End Class
更新
我看到Dictionary集合对象上的Item函数做了我想要的,但我仍然想知道为什么我得到上面提到的错误。
答案 0 :(得分:1)
错误1:当您通过词典进行枚举时,每个项目都是KeyValuePair,其中包含Key(在您的情况下为Integer类型)和值(在您的情况下为T类型)。所以你应该:
For Each currentItem As KeyValuePair(Of Integer, T) In Me
错误2:我认为错误信息非常清楚,但如果您执行上述更改,此行就可以了。 Key属性是KeyValuePair类的一部分,并获取字典键。
错误3:与错误1相同,查询字典时返回类型为KeyValuePair(Of Integer,T),而不是T.要检索实际值(类型为T),请使用KeyValuePair的Value属性:
Return (From X In Me Where X.Key = identity Select X.Value).FirstOrDefault