Created
December 17, 2017 06:27
-
-
Save ufcpp/08cb223b1b53a6cd0b13d953a0055156 to your computer and use it in GitHub Desktop.
構造体を mutable にするときは注意
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
struct Point | |
{ | |
public int X; | |
public int Y; | |
} | |
class Sample | |
{ | |
private Point _p; | |
public Point P => _p; // 戻り値でコピー発生 | |
public void X(Point p) // 引数でもコピー発生 | |
{ | |
p.X = 1; | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
// これは大丈夫 | |
var p = new Point(); | |
p.X = 1; | |
var s = new Sample(); | |
// そもそもコンパイル エラーになるから事故率は低い | |
// プロパティは、コピーが帰って来てるので書き換えたらダメ | |
s.P.X = 1; | |
// 戻り値を r で受け取った時点でコピー | |
// s.P には反映されない | |
var r = s.P; | |
r.X = 1; | |
// 引数にはコピーが渡るので p は書き換わらない | |
// それが意図してのことならいいんだけど | |
s.X(p); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment