Is it possible to override a property and return a derived type in VB.NET?

后端 未结 3 872
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 18:48

Consider the following classes representing an Ordering system:

Public Class OrderBase
    Public MustOverride Property OrderItem as OrderItemBase
End Class
         


        
3条回答
  •  旧巷少年郎
    2020-12-20 19:18

    One approach is to have a protected overridable method, and then have a public non-overridable method which calls the overridable one. Any time the return value for the function in the derived class should change, have a notoverridable override of the overridable method call a new overridable method which returns the more refined type, and also shadow the earlier version of the public function with one that uses the new override. If vb.net allowed one class to both override and shadow the same member, things would be much cleaner, but there's no way to do that.

    Public Class CarFactory
      Protected Overridable Function DerivedMakeCar() as Car
        ' make a car
      End Function
    
      Public Function MakeCar() as Car
        Return DerivedMakeCar()
      End Function
    
    End Class
    
    Public Class FordFactory
      Inherits CarFactory
    
      Protected Overrides Function DerivedMakeCar() As Car
        Return DerivedMakeFord()
      End Function
    
      Protected Overridable Function DerivedMakeFord() As Ford
        ' Make a Ford
      End Function
    
      Public Shadows Function MakeCar() As Ford
        Return DerivedMakeFord()
      End Function
    
    End Class
    

    A simpler alternative in some cases may be to have a public overridable MakeCar() function which always returns an object of type Car, but have a FordFactory also include a MakeFord() function which returns a Ford.

    The overridden MakeCar() function would be NotOverridable and would simply call MakeFord. In some ways, the latter approach can be cleaner, but if there's a common naming convention (e.g. factories have a MakeProduct method which returns the most derived type) it may be useful to use Shadows.

提交回复
热议问题