繁体   English   中英

如何在VB.NET的派生类中禁止基类的属性或方法?

[英]How can I supress a property or method from a base-class in a derived class in VB.NET?

假设一个基类

Public Class airplane

Private var_num_seats As Integer
Private var_num_engines As Integer

Protected Property num_seats As Integer
    Get
        Return var_num_seats
    End Get
    Set(ByVal param_num_seats As Integer)
        var_num_seats = param_num_seats
    End Set
End Property

Protected Friend Property num_engines As Integer
    Get
        Return var_num_engines

    End Get
    Set(ByVal param_num_engines As Integer)
        var_num_engines = param_num_engines
    End Set
End Property

Protected Friend Sub take_off()
    'Do take off tasks
End Sub

Protected Friend Sub start_engines()
    'start each engine
End Sub

End Class

还有一个儿童班

Public Class glider
Inherits airplane

Private var_towed As Boolean
Private var_glide_rate As Double

Public ReadOnly Property towed As Boolean
    Get
        Return var_towed
    End Get
End Property

Public ReadOnly Property glide_rate As Double
    Get
        Return var_glide_rate
    End Get
End Property

Public Sub to_glide()
    'do gliding
End Sub

End Class

显然,我不希望类Glider具有方法“ start_engines”和属性“ num_engines”。 否则,其他子类可能会有。 我如何在子类中禁止这些属性和方法,而不仅仅是忽略(如果可以的话)?

谢谢!

你不能!

原因:破坏了面向对象!!!!

假设您有:

public void ThisIsAMethod(Airplane plane)
{
    plane.start_engines();
}

现在,您可以这样使用它:

Airplane aPlane = new Glider();
ThisIsAMethod(aPlane);

哦,不,aPlane确实是滑翔机,因此您不应调用它。 然而,它是飞机,因此具有该方法。

解:

  1. 形成真正的继承。 滑翔机不是飞机。 也许您可以为“ FlyingMachine”或“ WingedFlier”或它们都扩展的东西提供基类。
  2. Hackmode! 在滑翔机中:

    受保护的好友Sub start_engines()抛出新的NotSupportedException()End Sub

我怀疑您正在寻找使用界面。

http://msdn.microsoft.com/en-us/library/h9xt0sdd.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM