声明
本文内容来自微软 MVP solenovex 的视频教程——真会C#?- 第3章 创建类型,大致和第 2 课—— class - 构造函数与析构函数 对应。可在 GitHub 中查看 C# 视频教程的配套PPT
本文主要包括以下内容:
- Constructors(构造函数)
- Deconstruct (解构函数)
Constructors(构造函数)
在 class 或 struct 上运行初始化代码。和定义方法差不多,但构造函数的名和类型名一致,返回类型也和类型一致,并且返回类型就省略不写了。C#7,允许单语句的构造函数写成 expression-bodied 成员的形式。
public class Panda
{
string name; // Define field
public Panda (string n) // Define constructor
{
name = n; // Initialization code (set up field)
}
// C#7
// public Panda (string n) => name = n;
}
...
Panda p = new Panda ("Petey"); // Call constructor
构造函数重载
class 和 struct 可以重载构造函数,调用重载构造函数时使用 this。当同一个类型下的构造函数 A 调用构造函数 B 的时候,B 先执行,可以把表达式传递给另一个构造函数,但表达式本身不能使用 this 引用,因为这时候对象还没有被初始化,所以对象上任何方法的调用都会失败。但是可以使用 static 方法。
using System;
public class Wine
{
public decimal Price;
public int Year;
public Wine (decimal price) { Price = price; }
public Wine (decimal price, int year) : this (price) { Year = year; }
}
无参构造函数
对于 class,如果你没有定义任何构造函数的话,那么 C# 编译器会自动生成一个无参的 public 构造函数。但是如果你定义了构造函数,那么这个无参的构造函数就不会被生成了。
构造函数和字段的初始化顺序
字段的初始化发生在构造函数执行之前,字段按照声明的先后顺序进行初始化。
class Player
{
int shields = 50; // Initialized first
int health = 100; // Initialized second
}
非 public 的构造函数
构造函数可以不是 public 的,如单例模式。
public class Class1
{
Class1() {} // Private constructor
public static Class1 Create (...)
{
// Perform custom logic here to return an instance of Class1
...
}
}
Deconstructor(C#7)(解构函数)
C#7 引入了 deconstructor 模式,作用基本和构造函数相反,它会把字段反赋给一堆变量。方法名必须是 Deconstruct, 有一个或多个 out 参数,Deconstructor 可以被重载,Deconstruct 这个方法可以是扩展方法。
class Rectangle
{
public readonly float Width, Height;
public Rectangle (float width, float height)
{
Width = width;
Height = height;
}
public void Deconstruct (out float width, out float height)
{
width = Width;
height = Height;
}
}
// To call the deconstructor, we use the following special syntax:
var rect = new Rectangle (3, 4);
(float width, float height) = rect; // Deconstruction
Console.WriteLine (width + " " + height); // 3 4

网友评论