C#之析構函數與構造函數
在學習C#時這兩個函數放到一起講了,聽課的時候感覺隻是有了膚淺的認識,於是查了一些資料,下麵做個比較全麵的理解。析構函數——垃圾回收器,它用來清理對象時調用
析構函數不能有參數,不能任何修飾符而且不能被調用,它是自動調用的,這是它與構造函數的一個主要區別。由於析構函數的目的與構造函數的相反,就加前綴‘~’以示區別。
class First
{
~First()
{
System.Diagnostics.Trace.WriteLine("First's destructor is called.");
}
}
class Second : First
{
~Second()
{
System.Diagnostics.Trace.WriteLine("Second's destructor is called.");
}
}
class Third : Second
{
~Third()
{
System.Diagnostics.Trace.WriteLine("Third's destructor is called.");
}
}
class TestDestructors
{
static void Main()
{
Third t = new Third();
}
}
這裏用到了派生, 類 First 是基類,Second 是從 First 派生的,而 Third 是從 Second 派生的。 這三個類都有析構函數。 在 Main() 中,創建了派生程度最大的類的實例。構造函數——初始化,它用來在對象調用時進行初始化,下麵是一段構造函數
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
//調用默認構造函數
Employee objEmployee = new Employee();
Console .WriteLine ("資格=" + objEmployee_qualification);
Console .WriteLine ("薪水=" + objEmployee_salary);
}
}
class Employee
{
private string _name;
private char _gender;
private string _qualification;
private uint _salary;
//默認構造函數
public Employee ()
{
_qualification = "研究生";
}
}
}
構造函數本身無返回值,它不能直接調用,隻有通過new運算符創建對象時才能調用,也就是上麵所說的初始化類,還有一點需要注意:隻有構造函數聲明為公有時才能被調用,私有是不能被調用的。構造函數可以是有函數的,也可以是沒有函數的。
最後更新:2017-04-03 12:54:47