VB.Net - 类和对象


当您定义类时,您就定义了数据类型的蓝图。这实际上并没有定义任何数据,但它确实定义了类名的含义,即该类的对象将由什么组成以及可以对此类对象执行哪些操作。

对象是类的实例。构成类的方法和变量称为类的成员。

类定义

类定义以关键字Class开头,后跟类名;和类主体,以 End Class 语句结束。以下是类定义的一般形式 -

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
   [ Inherits classname ]
   [ Implements interfacenames ]
   [ statements ]
End Class

在哪里,

  • attributelist是适用于该类的属性列表。选修的。

  • accessmodifier定义类的访问级别,其值为 - Public、Protected、Friend、Protected Friend 和 Private。选修的。

  • 阴影表示变量重新声明并隐藏基类中的同名元素或重载元素集。选修的。

  • MustInherit指定该类只能用作基类,并且不能直接从它创建对象,即抽象类。选修的。

  • NotInheritable指定该类不能用作基类。

  • Partial表示类的部分定义。

  • Inherits指定它所继承的基类。

  • Implements指定类继承的接口。

以下示例演示了一个 Box 类,具有三个数据成员:长度、宽度和高度 -

Module mybox
   Class Box
      Public length As Double   ' Length of a box
      Public breadth As Double  ' Breadth of a box
      Public height As Double   ' Height of a box
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box
      Dim volume As Double = 0.0         ' Store the volume of a box here
      
      ' box 1 specification
      Box1.height = 5.0
      Box1.length = 6.0
      Box1.breadth = 7.0
      
      ' box 2 specification
      Box2.height = 10.0
      Box2.length = 12.0	
      Box2.breadth = 13.0
      
      'volume of box 1
      volume = Box1.height * Box1.length * Box1.breadth
      Console.WriteLine("Volume of Box1 : {0}", volume)
      
      'volume of box 2
      volume = Box2.height * Box2.length * Box2.breadth
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

当上面的代码被编译并执行时,它会产生以下结果 -

Volume of Box1 : 210
Volume of Box2 : 1560

成员函数及封装

类的成员函数是像任何其他变量一样在类定义中具有其定义或原型的函数。它对它所属的类的任何对象进行操作,并且可以访问该对象的类的所有成员。

成员变量是对象的属性(从设计角度来看),并且它们保持私有以实现封装。这些变量只能使用公共成员函数来访问。

让我们将上述概念来设置和获取类中不同类成员的值 -

Module mybox
   Class Box
      Public length As Double    ' Length of a box
      Public breadth As Double   ' Breadth of a box
      Public height As Double    ' Height of a box
      Public Sub setLength(ByVal len As Double)
         length = len
      End Sub
      
      Public Sub setBreadth(ByVal bre As Double)
         breadth = bre
      End Sub
      
      Public Sub setHeight(ByVal hei As Double)
         height = hei
      End Sub
      
      Public Function getVolume() As Double
         Return length * breadth * height
      End Function
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box
      Dim volume As Double = 0.0         ' Store the volume of a box here

      ' box 1 specification
      Box1.setLength(6.0)
      Box1.setBreadth(7.0)
      Box1.setHeight(5.0)
      
      'box 2 specification
      Box2.setLength(12.0)
      Box2.setBreadth(13.0)
      Box2.setHeight(10.0)
      
      ' volume of box 1
      volume = Box1.getVolume()
      Console.WriteLine("Volume of Box1 : {0}", volume)

      'volume of box 2
      volume = Box2.getVolume()
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

当上面的代码被编译并执行时,它会产生以下结果 -

Volume of Box1 : 210
Volume of Box2 : 1560

构造函数和析构函数

构造函数是类的特殊成员 Sub,每当我们创建该类的新对象时都会执行它。构造函数的名称为New,并且没有任何返回类型。

以下程序解释了构造函数的概念 -

Class Line
   Private length As Double    ' Length of a line
   Public Sub New()   'constructor
      Console.WriteLine("Object is being created")
   End Sub
   
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
     
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line = New Line()
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class

当上面的代码被编译并执行时,它会产生以下结果 -

Object is being created
Length of line : 6

默认构造函数没有任何参数,但如果需要,构造函数可以有参数。此类构造函数称为参数化构造函数。此技术可帮助您在创建对象时为其分配初始值,如下例所示 -

Class Line
   Private length As Double    ' Length of a line
   Public Sub New(ByVal len As Double)   'parameterised constructor
      Console.WriteLine("Object is being created, length = {0}", len)
      length = len
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
       
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line = New Line(10.0)
      Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class

当上面的代码被编译并执行时,它会产生以下结果 -

Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6

析构函数是类的特殊成员 Sub,只要该类的对象超出范围,就会执行该析构函数。

析构函数的名称为Finalize,它既不能返回值,也不能接受任何参数。析构函数对于在退出程序之前释放资源非常有用,例如关闭文件、释放内存等。

析构函数不能被继承或重载。

以下示例解释了析构函数的概念 -

Class Line
   Private length As Double    ' Length of a line
   Public Sub New()   'parameterised constructor
      Console.WriteLine("Object is being created")
   End Sub
   
   Protected Overrides Sub Finalize()  ' destructor
      Console.WriteLine("Object is being deleted")
   End Sub
   
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
   
   Public Function getLength() As Double
      Return length
   End Function
   
   Shared Sub Main()
      Dim line As Line = New Line()
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class

当上面的代码被编译并执行时,它会产生以下结果 -

Object is being created
Length of line : 6
Object is being deleted

VB.Net 类的共享成员

我们可以使用 Shared 关键字将类成员定义为静态。当我们将类的成员声明为Shared时,就意味着无论创建该类的多少个对象,该成员都只有一份副本。

关键字Shared意味着一个类只存在一个成员实例。共享变量用于定义常量,因为可以通过调用类来检索它们的值,而无需创建类的实例。

共享变量可以在成员函数或类定义之外进行初始化。您还可以在类定义中初始化共享变量。

您还可以将成员函数声明为共享。此类函数只能访问共享变量。共享函数甚至在创建对象之前就存在。

以下示例演示了共享成员的使用 -

Class StaticVar
   Public Shared num As Integer
   Public Sub count()
      num = num + 1
   End Sub
   Public Shared Function getNum() As Integer
      Return num
   End Function
   Shared Sub Main()
      Dim s As StaticVar = New StaticVar()
      s.count()
      s.count()
      s.count()
      Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
      Console.ReadKey()
   End Sub
End Class

当上面的代码被编译并执行时,它会产生以下结果 -

Value of variable num: 3

遗产

面向对象编程中最重要的概念之一是继承。继承允许我们根据另一个类来定义一个类,这使得创建和维护应用程序变得更加容易。这也提供了重用代码功能和快速实施时间的机会。

创建类时,程序员可以指定新类继承现有类的成员,而不是编写全新的数据成员和成员函数。这个现有类称为类,新类称为派生类。

基类和派生类

一个类可以从多个类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。

VB.Net 中用于创建派生类的语法如下 -

<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class

考虑一个基类 Shape 及其派生类 Rectangle -

' Base class
Class Shape
   Protected width As Integer
   Protected height As Integer
   Public Sub setWidth(ByVal w As Integer)
      width = w
   End Sub
   Public Sub setHeight(ByVal h As Integer)
      height = h
   End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
   Public Function getArea() As Integer
      Return (width * height)
   End Function
End Class
Class RectangleTester
   Shared Sub Main()
      Dim rect As Rectangle = New Rectangle()
      rect.setWidth(5)
      rect.setHeight(7)
      ' Print the area of the object.
      Console.WriteLine("Total area: {0}", rect.getArea())
      Console.ReadKey()
   End Sub	
End Class

当上面的代码被编译并执行时,它会产生以下结果 -

Total area: 35

基类初始化

派生类继承了基类的成员变量和成员方法。因此,超类对象应该在创建子类之前创建。超类或基类在 VB.Net 中隐式称为MyBase

以下程序演示了这一点 -

' Base class
Class Rectangle
   Protected width As Double
   Protected length As Double
   Public Sub New(ByVal l As Double, ByVal w As Double)
      length = l
      width = w
   End Sub
   Public Function GetArea() As Double
      Return (width * length)
   End Function
   Public Overridable Sub Display()
      Console.WriteLine("Length: {0}", length)
      Console.WriteLine("Width: {0}", width)
      Console.WriteLine("Area: {0}", GetArea())
   End Sub
   'end class Rectangle  
End Class

'Derived class
Class Tabletop : Inherits Rectangle
   Private cost As Double
   Public Sub New(ByVal l As Double, ByVal w As Double)
      MyBase.New(l, w)
   End Sub
   Public Function GetCost() As Double
      Dim cost As Double
      cost = GetArea() * 70
      Return cost
   End Function
   Public Overrides Sub Display()
      MyBase.Display()
      Console.WriteLine("Cost: {0}", GetCost())
   End Sub
    'end class Tabletop
End Class
Class RectangleTester
   Shared Sub Main()
      Dim t As Tabletop = New Tabletop(4.5, 7.5)
      t.Display()
      Console.ReadKey()
   End Sub
End Class

当上面的代码被编译并执行时,它会产生以下结果 -

Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5

VB.Net 支持多重继承。