Can Someone Explain MustOverride?

2019-06-20 05:27发布

问题:

Can someone explain not what MustOverride does, but why use it? Is it to expose the function?

I have two classes, the first (RoomFactory);

Public MustInherit Class RoomFactory : Inherits baseFactory
Private _roomid As Integer = 0
Private _roomname as String = ""

Public Sub New()

End Sub

Public Sub New(ByVal roomid As Integer, ByVal roomname As String)
    Me.RoomId = roomid
    Me.RoomName = roomname
End Sub

Public MustOverride Function CreateRoom(ByVal roomdetails As RoomFactory) As Integer
Public MustOverride Function IsRoomAvailable(ByVal roomdetails as RoomFactory) As Boolean
// .. properties removed for brevity .. //

Second class (Room)

Public Class Room : Inherits RoomFactory
    Public Function CreateRoom(ByVal roomdetails As RoomFactory) As Integer
        Return 0
    End Function
    Public Function IsRoomAvailable(ByVal roomdetails As RoomFactory) As Boolean
        Return False
    End Function
End Class

Firstly, I think this is right, but would like any advice to the otherwise - performance etc. But I guess the primary question is - why use the MustOverride?

Please excuse my ignorance here.

回答1:

It's so that you can provide common functionality in a base class, but force derived classes to implement specific bits of functionality themselves.

In your factory situation I would suggest using an interface rather than an abstract class, but in other cases it makes sense. System.Text.Encoding is a good example of an abstract class, as is System.IO.Stream.



回答2:

You would use Overrideable for a method that has a default implementation in the base class.
When no (sensible) default implementation is possible, use Mustoverride.



回答3:

I am no VB.NET expert but surely done C#. In C# the equivalent is abstract keyword. It should be used in cases where you want all the classes deriving from your RoomFactory class to implement some behavior you defined as abstract.

Suppose in your example, if you want all Room objects created inherited from the RoomFactory class to return its size. You would create a mustoverride function say ReturnSize in Roomfactory and any type of room which inherits from this should implement this function.

You could do the same thing with interfaces. But using such MustInherit class allows you to add some default behavior in RoomFactory which will be common to all rooms.

Hope this helps.



回答4:

MustOverride specifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can be used.