Imports System.Collections
Class A
Private x As Integer = 1
Private y As Integer = - 1
Private count As Integer
Public Sub New()
count = 0
End Sub
Public Sub New(n As Integer)
count = n
End Sub
End Class
Class B
Inherits A
Private sqrt2 As Double = Math.Sqrt(2.0)
Private items As New ArrayList(100)
Private max As Integer
Public Sub New()
Me.New(100)
items.Add("default")
End Sub
Public Sub New(n As Integer)
MyBase.New(n-1)
max = n
End Sub
End Class
此例对应于下面显示的代码,其中的每个注释都指示一个自动插入的语句:
Imports System.Collections
Class A
Private x, y, count As Integer
Public Sub New()
MyBase.New() ' Invoke object() constructor.
x = 1 ' This is a variable initializer.
y = - 1 ' This is a variable initializer.
count = 0
End Sub
Public Sub New(n As Integer)
MyBase.New() ' Invoke Object constructor.
x = 1 ' This is a variable initializer.
y = - 1 ' This is a variable initializer.
count = n
End Sub
End Class
Class B
Inherits A
Private sqrt2 As Double
Private items As ArrayList
Private max As Integer
Public Sub New()
Me.New(100)
items.Add("default")
End Sub
Public Sub New(n As Integer)
MyBase.New(n - 1)
sqrt2 = System.Math.Sqrt(2.0) ' This is a variable initializer.
items = New ArrayList(100) ' This is a variable initializer.
max = n
End Sub
End Class
注意,变量初始值设定项被转换为赋值语句,而这些赋值语句在基类构造函数调用“之后”执行。这种顺序确保了所有基实例变量在可访问实例的“任何”语句执行之前,由它们的变量初始值设定项初始化,如下例所示:
Class A
Dim x As Integer = 1
End Class
Class B
Inherits A
Private y As Integer = x
Public Sub New()
Console.WriteLine("x = " & x & ", y = " & y)
End Sub
End Class
当使用 New B() 创建 B 的实例时,产生如下输出结果:
示例
下面的示例创建三个类,这三个类构成了一个继承链。类 First 是基类,Second 是从 First 派生的,而 Third 是从 Second 派生的。这三个类都有析构函数。在 Main() 中,创建了派生相近程度最大的类的实例。程序运行时,注意这三个类的析构函数会自动被调用,并且是按照从派生相近程度最大的到派生相近程度最小的次序调用。
// Destructors1.cs
using System;
class First
{
~First()
{
Console.WriteLine("First's destructor is called");
}
}
class Second: First
{
~Second()
{
Console.WriteLine("Second's destructor is called");
}
}
class Third: Second
{
~Third()
{
Console.WriteLine("Third's destructor is called");
}
}
public class MainClass
{
public static void Main()
{
Third myObject = new Third();
}
}
输出
Third's destructor is called
Second's destructor is called
First's destructor is called
使用析构函数释放资源
一般来说,您不必像使用 C++ 时那样关注内存管理。这是因为 .NET Framework 垃圾回收器会隐式地管理对象的内存分配和释放。但是,当应用程序封装窗口、文件和网络连接这类非托管资源时,应当使用析构函数释放这些资源。当对象符合销毁条件时,垃圾回收器会运行对象的 Finalize 方法。