代码之家  ›  专栏  ›  技术社区  ›  dooburt

有人能解释一下吗?

  •  6
  • dooburt  · 技术社区  · 15 年前

    我有两个班,第一个(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 .. //
    

    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
    

    首先,我认为这是正确的,但我想对其他方面提出建议-性能等。但我想主要问题是-为什么要使用MustOverride?

    4 回复  |  直到 15 年前
        1
  •  10
  •   Jon Skeet    15 年前

    这样,您可以在基类中提供公共功能,但强制派生类自己实现特定的功能。

    在工厂环境中,我建议使用接口而不是抽象类,但在其他情况下,这是有意义的。 System.Text.Encoding System.IO.Stream .

        2
  •  4
  •   Henk Holterman    15 年前

    Overrideable 对于基类中具有默认实现的方法。
    如果没有(合理的)默认实现,请使用 Mustoverride

        3
  •  3
  •   theraneman    15 年前

    我不是VB.NET专家,但肯定是C。在C#中,等价物是抽象关键字。当您希望从RoomFactory类派生的所有类实现您定义为抽象的某些行为时,应该使用它。

    假设在示例中,希望从RoomFactory类继承创建的所有房间对象返回其大小。您可以在Roomfactory中创建一个mustoverride函数,比如ReturnSize,从该函数继承的任何类型的房间都应该实现该函数。

    您可以对接口执行相同的操作。但是使用这样的MustInherit类允许您在RoomFactory中添加一些默认行为,这对所有房间都是通用的。

        4
  •  1
  •   Martin    15 年前

    MustOverride指定属性或过程不在此类中实现,必须在派生类中重写,才能使用。