我试图创建一个应用程序,在这个应用程序中,我有一个包含对象的List(of T)
集合。
处理对象时,我需要从列表中知道它的索引。
示例:
Public Class
Public oList as New List(of TestObject)
Private Sub Test()
Dim NewObject As New TestObject
oList.add(NewObject)
Index(NewObject)
End Sub
Private Sub Index(Byval TestObject As TestObject)
debug.print(Testobject.index)
End Sub
End Class
这样的事情可能吗?我已经看到它在我前一段时间使用的参考文件中可用,但现在我想在我自己的课程中提供它。
有人可以提供样品吗?
PS:我知道我可以使用List(Of T).IndexOf Method (T)
获取索引但是为了将来的可能性,我想从对象本身进行调用。
答案 0 :(得分:1)
看起来像这样
Public oList As New List(Of TestObject)
Private Sub Test()
Dim NewObject As New TestObject(oList.Count)
oList.add(NewObject)
End Sub
Public Class TestObject
Public index As Integer
Public Sub New(IndxOfObj As Integer)
Me.index = IndxOfObj
End Sub
End Class
答案 1 :(得分:1)
通常情况下,他们有一个自定义列表,他们不直接使用List(Of T),并在将该项添加到列表中时将列表存储在对象中。
Module Module1
Sub Main()
Dim someList As New CustomList
someList.Add(New CustomItem())
someList.Add(New CustomItem())
someList.Add(New CustomItem())
Console.WriteLine(someList(1).Index)
Console.ReadLine()
End Sub
End Module
Class CustomItem
' Friend since we don't want anyone else to see/change it.
Friend IncludedInList As CustomList
Public ReadOnly Property Index
Get
If IncludedInList Is Nothing Then
Return -1
End If
Return IncludedInList.IndexOf(Me)
End Get
End Property
End Class
Class CustomList
Inherits System.Collections.ObjectModel.Collection(Of CustomItem)
Protected Overrides Sub InsertItem(index As Integer, item As CustomItem)
If item.IncludedInList IsNot Nothing Then
Throw New ArgumentException("Item already in a list")
End If
item.IncludedInList = Me
MyBase.InsertItem(index, item)
End Sub
Protected Overrides Sub RemoveItem(index As Integer)
Me(index).IncludedInList = Nothing
MyBase.RemoveItem(index)
End Sub
End Class
答案 2 :(得分:0)
如果您需要将其作为对象的属性,我建议如下:
minus = '-'
NegNum = [int(minus + str(i)) for i in PosList]
NegNum
(Output)[-1, -2, -3, -4, -5]
如果您碰巧将Main类作为Singleton,您可以跳过整个发送'Me'到构造函数业务中。然后,您只需调用Main.Index,而不将其作为属性存储在所有TestObjects上。