我有一个列表
Public Class Connoisseur
Public Name As String
Public Pieces As String
End Class
Private Sub Button26_Click(sender As Object, e As RibbonControlEventArgs) Handles Button26.Click
Dim CS As New List(Of Connoisseur)()
End Sub
如何使用泛型编写IFNotExistsAdd函数
CS = {"test1","2"}
看起来是这样的
CS.IFNotExistsAdd(New Connoisseur() With{.Name="test1",.Pieces="1"}) 'This line will not be added because CS.Name already contains "test1"
CS.IFNotExistsAdd(New Connoisseur() With{.Name="test2",.Pieces="1"})
输出如下所示
输出:
{"test1","2"}
{"test2","1"}
你的问题不是很清楚。IFNotExistsAdd不是List的有效方法名,所以你必须创建一个扩展方法。
创建一个模块(使用与调用类相同的命名空间)
Module Extensions
<Extension>
Public Sub IFNotExistsAdd(Of T)(list As List(Of T), item As T)
If Not list.Any(Function(x) x.Equals(item)) Then
list.Add(item)
End If
End Sub
End Module
然后你需要在类中添加一个Equals覆盖(我还为属性添加了一个初始化器)
Public Class Connoisseur
Public Name As String
Public Pieces As String
Public Sub New(name As String, pieces As String)
Me.Name = name
Me.Pieces = pieces
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
If TypeOf obj Is Connoisseur Then
Return EqualsItem(CType(obj, Connoisseur))
Else
Return False
End If
End Function
Public Function EqualsItem(obj As Connoisseur) As Boolean
Return obj.Name = Me.Name And obj.Pieces = Me.Pieces
End Function
End Class
你可以运行add items to list,它只会添加那些唯一的
CS.IFNotExistsAdd(New Connoisseur("test1", 1))
CS.IFNotExistsAdd(New Connoisseur("test1", 1))
CS.IFNotExistsAdd(New Connoisseur("test2", 2))
这将只添加test1和test2。