構造函數是在創建給定類型的對象時執行的類方法。 構造函數具有與類相同的名稱,它通常初始化新對象的數據成員。
在下面的示例中,使用一個簡單的構造函數定義了名爲 Taxi 的類。 然後使用 new 運算符來實例化該類。 在爲新對象分配內存之後,new 運算符立即調用 Taxi 構造函數。
public class Taxi
{
public bool isInitialized;
public Taxi()
{
isInitialized = true;
}
}
class TestTaxi
{
static void Main()
{
Taxi t = new Taxi();
Console.WriteLine(t.isInitialized);
}
}
不帶參數的構造函數稱爲“默認構造函數”。
無論何時,只要使用 new 運算符實例化對象,並且不爲
new 提供任何參數,就會調用默認構造函數。
下面的示例說明包含兩個類構造函數的類:一個類構造函數沒有參數,另一個類構造函數帶有兩個參數。
class CoOrds
{
public int x, y;
// Default constructor:
public CoOrds()
{
x = 0;
y = 0;
}
// tcA constructor with two arguments:
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
// Override the ToString method:
public override string ToString()
{
return (String.Format("({0},{1})", x, y));
}
}
class MainClass
{
static void Main()
{
CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);
// Display the results using the overriden ToString method:
Console.WriteLine("CoOrds #1 at {0}", p1);
Console.WriteLine("CoOrds #2 at {0}", p2);
Console.ReadKey();
}
}
/* Output:
CoOrds #1 at (0,0)
CoOrds #2 at (5,3)
*/