Created
March 25, 2017 00:25
-
-
Save ichiroku11/5e3ea783f9d7c2d63a27c78ac221d63d to your computer and use it in GitHub Desktop.
Getterのみの自動実装プロパティの初期化子のメモ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Runtime.CompilerServices; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| namespace ConsoleApp { | |
| class Sample { | |
| private static int GetValue([CallerMemberName]string caller = null) { | |
| // どのプロパティから呼ばれたか | |
| Console.WriteLine($"#{nameof(GetValue)} from {caller}"); | |
| return 1; // 値に意味なし | |
| } | |
| public Sample() { | |
| Console.WriteLine($"#{nameof(Sample)} Constructor"); | |
| } | |
| // 自動実装プロパティの初期化子 | |
| public int Value1 { get; } = GetValue(); | |
| // ラムダ式本体によるプロパティ | |
| public int Value2 => GetValue(); | |
| } | |
| class Program { | |
| static void Main(string[] args) { | |
| // Value1プロパティのGetValueメソッドは、 | |
| // newしたタイミングでコンストラクタ本体より先に実行される | |
| Console.WriteLine($"new {nameof(Sample)}()"); | |
| var sample = new Sample(); | |
| // 結果: | |
| //new Sample() | |
| //#GetValue from Value1 | |
| //#Sample Constructor | |
| // Value1プロパティを参照してもGetValueメソッドは実行されない | |
| Console.WriteLine($"{nameof(sample.Value1)}"); | |
| var value1 = sample.Value1; | |
| // 結果: | |
| //Value1 | |
| // Value2プロパティを参照するごとにGetValueメソッドが実行される | |
| Console.WriteLine($"{nameof(sample.Value2)}"); | |
| var value2 = sample.Value2; | |
| // 結果: | |
| //Value2 | |
| //#GetValue from Value2 | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment