Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created March 25, 2017 00:25
Show Gist options
  • Select an option

  • Save ichiroku11/5e3ea783f9d7c2d63a27c78ac221d63d to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/5e3ea783f9d7c2d63a27c78ac221d63d to your computer and use it in GitHub Desktop.
Getterのみの自動実装プロパティの初期化子のメモ
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