Last active
August 1, 2017 15:35
-
-
Save onionmk2/72ce425c56cbfd36fc1061040edce813 to your computer and use it in GitHub Desktop.
値と参照。
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
void Main() | |
{ | |
var x = 1; | |
Assign2ToValue(x); | |
x.Dump(); | |
OutAssign3ToValue(out x); | |
x.Dump(); | |
var y = new int[] { 4 }; | |
var z = new int[] { 5 }; | |
AssignToReference__TryUpdateSelf(y, z); | |
y.Dump(); | |
AssignToReference__UpdateItem(y, 6); | |
y.Dump(); | |
var w = new int[] {7}; | |
OutAssignToReference(out w, z); | |
w.Dump(); | |
var humans = new List<Human> { new Human {name="X"}}; | |
TryToChange(humans); | |
humans.Dump(); | |
Update(humans); | |
humans.Dump(); | |
Change(out humans); | |
humans.Dump(); | |
} | |
// 値型の値渡し | |
void Assign2ToValue(int a) { | |
a = 2; | |
} | |
// 値型の参照渡し | |
void OutAssign3ToValue(out int a) | |
{ | |
a = 3; | |
} | |
// 参照型の値渡し。引数自体に代入。 | |
void AssignToReference__TryUpdateSelf(int[] a, int[] b) | |
{ | |
a = b; // この変更は AssignToReference__TryUpdateSelf の中でのみ有効。 | |
("a[0] is " + a[0] + " at AssignToReference__TryUpdateSelf").Dump(); | |
} | |
// 参照型の値渡し。引数のitemに代入 | |
void AssignToReference__UpdateItem(int[] a, int b) | |
{ | |
a[0] = b; // この変更は、AssignToReference__UpdateItemの外でも有効。 | |
} | |
// 参照型の参照渡し | |
void OutAssignToReference(out int[]a, int[]b) | |
{ | |
a = b; | |
} | |
class Human { | |
public string name; | |
} | |
void TryToChange(List<Human> humans) | |
{ | |
humans = new List<Human> { | |
new Human {name = "A"} | |
}; | |
} | |
void Update(List<Human> humans) | |
{ | |
humans.Add(new Human { name = "B"}); | |
} | |
void Change(out List<Human> humans) | |
{ | |
humans = new List<Human> { | |
new Human {name = "C"} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://docs.microsoft.com/ja-jp/dotnet/csharp/programming-guide/classes-and-structs/passing-reference-type-parameters