Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created January 7, 2020 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufcpp/2517a4c9e3c845e5d4ec286cc24c1824 to your computer and use it in GitHub Desktop.
Save ufcpp/2517a4c9e3c845e5d4ec286cc24c1824 to your computer and use it in GitHub Desktop.
readonly メソッド、ちゃんとフィールドの構造体が書き換わらないようにコピー取るみたい
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