選單
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP How to W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C# 建構函式


建構函式

建構函式是用於**初始化物件**的**特殊方法**。建構函式的優點是,在建立類物件時會自動呼叫它。它可以用於為欄位設定初始值。

示例

建立建構函式

// Create a Car class
class Car
{
  public string model;  // Create a field

  // Create a class constructor for the Car class
  public Car()
  {
    model = "Mustang"; // Set the initial value for model
  }

  static void Main(string[] args)
  {
    Car Ford = new Car();  // Create an object of the Car Class (this will call the constructor)
    Console.WriteLine(Ford.model);  // Print the value of model
  }
}

// Outputs "Mustang"

自己動手試一試 »

請注意,建構函式的名稱必須**與類名匹配**,並且它不能有**返回型別**(例如 voidint)。

另外請注意,在建立物件時會呼叫建構函式。

所有類預設都有建構函式:如果您不自己建立類建構函式,C# 會為您建立一個。但是,這樣您就無法為欄位設定初始值。

建構函式節省時間! 檢視此頁面上的最後一個示例,以真正理解原因。



構造方法引數

建構函式也可以接受引數,這用於初始化欄位。

以下示例向建構函式添加了一個 string modelName 引數。在建構函式內部,我們將 model 設定為 modelNamemodel=modelName)。當我們呼叫建構函式時,我們會向建構函式傳遞一個引數("Mustang"),這將把 model 的值設定為 "Mustang"

示例

class Car
{
  public string model;

  // Create a class constructor with a parameter
  public Car(string modelName)
  {
    model = modelName;
  }

  static void Main(string[] args)
  {
    Car Ford = new Car("Mustang");
    Console.WriteLine(Ford.model);
  }
}

// Outputs "Mustang"

自己動手試一試 »

您可以擁有任意數量的引數

示例

class Car
{
  public string model;
  public string color;
  public int year;

  // Create a class constructor with multiple parameters
  public Car(string modelName, string modelColor, int modelYear)
  {
    model = modelName;
    color = modelColor;
    year = modelYear;
  }

  static void Main(string[] args)
  {
    Car Ford = new Car("Mustang", "Red", 1969);
    Console.WriteLine(Ford.color + " " + Ford.year + " " + Ford.model);
  }
}


// Outputs Red 1969 Mustang

自己動手試一試 »

提示: 就像其他方法一樣,可以透過使用不同數量的引數來**過載**建構函式。


建構函式節省時間

當您考慮上一章中的示例時,您會注意到建構函式非常有用,因為它們有助於減少程式碼量。

無建構函式

prog.cs

class Program
{
  static void Main(string[] args)
  {
    Car Ford = new Car();
    Ford.model = "Mustang";
    Ford.color = "red";
    Ford.year = 1969;

    Car Opel = new Car();
    Opel.model = "Astra";
    Opel.color = "white";
    Opel.year = 2005;

    Console.WriteLine(Ford.model);
    Console.WriteLine(Opel.model);
  }
}

自己動手試一試 »

有建構函式

prog.cs

class Program
{
  static void Main(string[] args)
  {
    Car Ford = new Car("Mustang", "Red", 1969);
    Car Opel = new Car("Astra", "White", 2005);

    Console.WriteLine(Ford.model);
    Console.WriteLine(Opel.model);
  }
}

自己動手試一試 »


×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援