Menu
×
   ❮   
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 设置为 modelName (model=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);
  }
}

自己尝试 »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.