是否可以覆盖属性并在VB.NET中返回派生类型? [英] Is it possible to override a property and return a derived type in VB.NET?
问题描述
考虑以下代表订购系统的类:
Consider the following classes representing an Ordering system:
Public Class OrderBase
Public MustOverride Property OrderItem as OrderItemBase
End Class
Public Class OrderItemBase
End Class
现在,假设我们想要将这些类扩展到更具体的订单类集,保持OrderBase的聚合性质:
Now, suppose we want to extend these classes to a more specific set of order classes, keeping the aggregate nature of OrderBase:
Public Class WebOrder
Inherits OrderBase
Public Overrides Property OrderItem as WebOrderItem
End Property
End Class
Public Class WebOrderItem
Inherits OrderItemBase
End Class
WebOrder类中的Overriden属性将导致错误声明返回类型与OrderBase中定义的类型不同...但是,返回类型是OrderBase中定义的类型的子类。为什么VB不允许这样做?
The Overriden property in the WebOrder class will cause an error stating that the return type is different from that defined in OrderBase... however, the return type is a subclass of the type defined in OrderBase. Why won't VB allow this?
推荐答案
你不能这样做 - 它正在改变基础上定义的签名。要做你想做的事,你需要使用泛型:
You can't do that - it's changing the signature defined on the base. To do what you are trying to do you need to use generics:
Public Class OrderBase(Of T As IOrderItem)
Public ReadOnly Property OrderItems As IList(Of T)
End Class
我的Visual Basic是生锈,所以希望这是准确的......
My Visual Basic is rusty so hopefully that is accurate...
这篇关于是否可以覆盖属性并在VB.NET中返回派生类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!