简体   繁体   English

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

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

Supose a base class 假设一个基类

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

And a child 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

Obviously, I don't wish that the class Glider has the method "start_engines" neither the property "num_engines". 显然,我不希望类Glider具有方法“ start_engines”和属性“ num_engines”。 Otherwise, other child classes may have. 否则,其他子类可能会有。 How can I supress these property and method in child class, not just ignoring (if I can)? 我如何在子类中禁止这些属性和方法,而不仅仅是忽略(如果可以的话)?

Thanks! 谢谢!

You Cant! 你不能!

Reason: Breaks object orientedness!!!! 原因:破坏了面向对象!!!!

Suppose you have: 假设您有:

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

Now you use it as such: 现在,您可以这样使用它:

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

Oh no, aPlane is really a glider, and hence you shouldn't be able to call it. 哦,不,aPlane确实是滑翔机,因此您不应调用它。 However, it is an airplane and thus has the method. 然而,它是飞机,因此具有该方法。

Solution: 解:

  1. Form a true inheritence. 形成真正的继承。 A glider is not an airplane. 滑翔机不是飞机。 Maybe you can have a base class for "FlyingMachine" or "WingedFlier" or something which they both extend. 也许您可以为“ FlyingMachine”或“ WingedFlier”或它们都扩展的东西提供基类。
  2. Hackmode! Hackmode! In Glider: 在滑翔机中:

    Protected Friend Sub start_engines() throw new NotSupportedException() End Sub 受保护的好友Sub start_engines()抛出新的NotSupportedException()End Sub

I suspect you're looking to use an interface. 我怀疑您正在寻找使用界面。

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

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

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