问题从继承名单(T)的类 [英] Question inheriting from List(of T) class
问题描述
我想实现一个优先级队列类。当一个项目被添加在一个更高的优先级将其推到的队列,而不是添加到队列的末尾的前
I want to implement a priority queue class. When an item is added at a higher priority it is pushed to the front of the queue instead adding to the end of queue.
的code简单的几行
Public Class PriorityQueue(Of T)
Inherits List(Of T)
Private _list As New List(Of T)
Public Sub Enque(ByVal item As T, Optional ByVal pushToFront As Boolean = False)
If pushToFront = True Then
_list.Insert(0, item)
Else
_list.Add(item)
End If
End Sub
Public Function Deque() As T
If _list.Count <> 0 Then
Dim item As T = _list(0)
_list.RemoveAt(0)
Return item
Else
Throw New InvalidOperationException
End If
End Function
End Class
现在的调用函数试图找到在队列中的元素从而 ......
Now the the calling function tries to find the elements in the queue thus ....
dim _q as new PriorityQueue(Of integer)
_q.Enque(1)
_q.Enque(2)
msgbox(_q.Count())
......
.....
程序打印出0!如果加计数()属性,然后一切都很好。 我本来以为继承的类应该调用基类的计数功能。 需要注意的是伯爵显示在智能感知,即使我已经在派生类中没有实现。
the program prints out 0! If add a Count() property then everything is fine. I would have thought the inherited class should call the base class's Count function. Note that the Count shows up in intellisense even if I have no implementation in the derived class.
推荐答案
您的问题是,你无论从列表
(的T)继承,你有一个实例这种类型,这就是你存储数据的属性。当计数
被称为在上述code,它使用了计数
属性从父名单(对T)
,这是不是你要存储的数据。
Your issue is that you're both inheriting from List(of T)
and you have an instance property of that type, which is where you're storing your data. When Count
is called in your above code, it's using the Count
property from your parent List(of T)
, which isn't where you're storing your data.
有一个更好的主意将是你从对象
继承和具有的PriorityQueue(T的)
实施的ICollection
和的IEnumerable(对T)
明确。你不应该改变你的内部实现在所有的,你只需要添加code,以支持这些接口。
A better idea would be for you to inherit from object
and have PriorityQueue(of T)
implement ICollection
and IEnumerable(of T)
explicitly. You shouldn't have to change your internal implementation at all, you'll just have to add code to support those interfaces.
这篇关于问题从继承名单(T)的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!