Skip to content

Commit 1ffac66

Browse files
authored
Merge pull request #15 from devlights/csharp7-new-feature-deconstructors
Add C# 7.0 Deconstructors example
2 parents f9c94f0 + 1f96705 commit 1ffac66

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Diff for: TryCSharp.Samples/CSharp7/Deconstructors.cs

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using TryCSharp.Common;
2+
3+
namespace TryCSharp.Samples.CSharp7
4+
{
5+
[Sample]
6+
public class Deconstructors : IExecutable
7+
{
8+
class Data
9+
{
10+
private readonly int _x;
11+
private readonly int _y;
12+
13+
public Data(int x, int y)
14+
{
15+
this._x = x;
16+
this._y = y;
17+
}
18+
19+
public void Deconstruct(out int x, out int y)
20+
{
21+
x = this._x;
22+
y = this._y;
23+
}
24+
}
25+
26+
public void Execute()
27+
{
28+
// C# 7.0 で deconstructor パターンが導入された
29+
// deconstructor とは コンストラクタの逆の事を示す
30+
// つまり、オブジェクト自身を右辺に配置した場合に自身の内容を
31+
// 「分解」して返却するための機能
32+
// deconstructor は 決まった書式で以下の様に記載する
33+
// public void Deconstruct(out xxx a, out xxx b)
34+
var d = new Data(1, 2);
35+
36+
// ここで deconstructor が呼ばれる
37+
var (x, y) = d;
38+
39+
Output.WriteLine($"{x}-{y}");
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)