构造函数

运行class或struct的初始化代码
和方法差不多,方法名和类型一致,返回类型也和类型一致。

  1. class name
  2. {
  3. public name()
  4. {
  5. }
  6. }

C#7,允许但语句的构造函数携程expression-bodied成员的形式

  1. class name
  2. {
  3. name() => Console.Wirte("Hello");
  4. }

构造函数重载

class和struct可以重载函数(和方法同理)
调用重载构造函数时使用this

  1. class classname
  2. {
  3. public decimal Price = 0m;
  4. public int Year;
  5. public classname(decimal price) { Price = price; }
  6. public classname(decimal price, int year) : this(price) { Year = year; }
  7. }

可以把表达式传递给另一个构造函数,但表达式本身不能使用this引用,因为这时候对象还没有被初始化,所以对象上任何方法的调用都会失败。但是可以使用static方法

无参构造函数

对于class,如果你没有定义任何构造函数的话,那么C#编译器会自动生成一个无参构造函数
但是如果你定义了构造函数,那么这个无参的构造函数就不会被生成了

构造函数和字段的初始化顺序

字段的初始化发生在构造函数执行之前
字段按照声明的先后顺序进行初始化

非PUBLIC的构造函数

构造函数可以不是public

  1. class name
  2. {
  3. static void Main()
  4. {
  5. var wine = Wine.CreateInstance();
  6. }
  7. }
  8. public class Wine
  9. {
  10. Wine() { }
  11. public static Wine CreateInstance()
  12. {
  13. return new Wine();
  14. }
  15. }

DECONSTRUCTOR(C#7)

C#7引入了deconstructor模式
作用基本和构造函数相反,它会把字段反赋给一堆变量
方法名必须是Deconstruct,有一个或多个out参数

  1. class Rectangle
  2. {
  3. public readonly float Width, Height;
  4. public Rectangle(float width, float height)
  5. {
  6. Width = width;
  7. Height = height;
  8. }
  9. public void Deconstruct(out float width, out float height)
  10. {
  11. width = Width;
  12. height = Height;
  13. }
  14. }
  15. class Test
  16. {
  17. public static void Main(string[] args)
  18. {
  19. var rect = new Rectangle(3, 4);
  20. //(float width, float height) = rect; // = 左边对应的Deconstruct方法里面的两个参数
  21. //实际上可以用下面的方式来写
  22. float width, height;
  23. rect.Deconstruct(out width, out height);
  24. System.Console.WriteLine(width + " " + height);
  25. }
  26. }

Deconstructor可以被重载
Deconstruct这个方法可以是扩展方法