C# 7 Deconstructor

CSharp · Console

/Program.cs

using System;
using System.Collections;

public class Program
{
	public static void Main()
	{
		var box = new Box(20, 50);
		var(width, height) = box; // 將 box 物件分解成兩個變數
		Console.WriteLine($"寬={width}, 高={height}");
	}

	public class Box
	{
		public int Width
		{
			get;
		} // 唯讀的自動屬性

		public int Height
		{
			get;
		} // 唯讀的自動屬性

		// 建構式(constructor)
		public Box(int width, int height)
		{
			Width = width;
			Height = height;
		}

		// 分解式(deconstructor)
		public void Deconstruct(out int width, out int height)
		{
			width = this.Width;
			height = this.Height;
		}
		
	    // 請留意建構式和分解式兩者的相似與相異處;
	    // 在設計類別時,你可能會想要同時提供這兩種方法。
	}
}
;