Created
January 7, 2020 01:27
-
-
Save ufcpp/2517a4c9e3c845e5d4ec286cc24c1824 to your computer and use it in GitHub Desktop.
readonly メソッド、ちゃんとフィールドの構造体が書き換わらないようにコピー取るみたい
This file contains 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; | |
struct A | |
{ | |
public int Value; | |
public void Increment() => Value++; | |
} | |
struct B | |
{ | |
public A A; | |
// A の非 readonly メンバーを呼ぶ。 | |
public void Mutable() => A.Increment(); | |
// Mutable との差は readonly 修飾が付いてるだけ。 | |
// this が書き換わらないように、A のコピーが作られる。A 自体には変化が起きない。 | |
public readonly void Immutable() => A.Increment(); | |
} | |
static class Program | |
{ | |
static void Main() | |
{ | |
var b = new B(); | |
// 1, 2, 3 | |
for (int i = 0; i < 3; i++) | |
{ | |
b.Mutable(); | |
Console.WriteLine(b.A.Value); | |
} | |
b = new B(); | |
// 0, 0, 0 (b.A が書き換わらない) | |
for (int i = 0; i < 3; i++) | |
{ | |
b.Immutable(); | |
Console.WriteLine(b.A.Value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment