MustInherit (Visual Basic)

指定类只能用作基类,并且不能直接从该基类创建对象。

注解

基类(也称为抽象类)的目的是定义派生自该类的所有类通用的功能。 这样,派生类就不必重新定义公共元素。 在某些情况下,此常见功能不够完整,无法生成一个可用对象,并且每个派生类都定义了缺少的功能。 在这种情况下,你希望使用的代码仅从派生类创建对象。 在基类上使用此 MustInherit 基类来强制执行此作。

类的另 MustInherit 一个用途是将变量限制为一组相关类。 可以定义基类并从中派生所有这些相关类。 基类不需要提供所有派生类通用的任何功能,但它可以用作将值分配给变量的筛选器。 如果你的使用代码将变量声明为基类,则 Visual Basic 仅允许将一个对象从其中一个派生类分配给该变量。

.NET Framework 定义多个MustInherit类,其中包括ArrayEnumValueTypeValueType 是限制变量的基类的示例。 所有值类型派生自 ValueType. 如果将变量声明为 ValueType变量,则只能向该变量分配值类型。

规则

  • 声明上下文。 只能在 MustInherit 语句中使用 Class

  • 组合修饰符。 不能在同MustInherit一声明中一起指定NotInheritable

示例:

以下示例演示了强制继承和强制重写。 基类 shape 定义变量 acrossLine。 类 circlesquare 派生自 shape。 它们继承了 acrossLine定义,但它们必须定义函数 area ,因为每种形状的计算都是不同的。

Public MustInherit Class shape
    Public acrossLine As Double
    Public MustOverride Function area() As Double
End Class
Public Class circle : Inherits shape
    Public Overrides Function area() As Double
        Return Math.PI * acrossLine
    End Function
End Class
Public Class square : Inherits shape
    Public Overrides Function area() As Double
        Return acrossLine * acrossLine
    End Function
End Class
Public Class consumeShapes
    Public Sub makeShapes()
        Dim shape1, shape2 As shape
        shape1 = New circle
        shape2 = New square
    End Sub
End Class

可以声明 shape1shape2 指定类型 shape。 但是,无法从 shape 中创建对象,因为它缺少函数 area 的功能并标记 MustInherit

由于它们被声明为 shape变量, shape1 并且 shape2 仅限于派生类 circle 中的对象和 square。 Visual Basic 不允许向这些变量分配任何其他对象,从而提供高级别的类型安全性。

用法

修饰 MustInherit 符可用于此上下文:

类声明

另请参阅