Hallo, kan iemand mij misschien uitleggen waarom deze code het volgende resultaat geeft?
Het punt is dus dat er een referentie wordt gelegd naar intList zodra intList2 wordt aangemaakt, maar hoe kan ik nu voorspellen dat er een referentie wordt gemaakt, en geen kopie zoals bij de Strings? M.a.w. hoe weet ik of iets een value type is of een reference type is? Dus hoe weet ik dat ik een copy/clone moet maken?
C#:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| String a, b = "b"; a = b; a = "a"; List<String> stringList1 = new List<String>(); stringList1.Add("1.1"); stringList1.Add("1.2"); stringList1.Add("1.3"); List<String> stringList2 = stringList1; stringList2.Add("2.1"); stringList2.Add("2.2"); stringList2.Add("2.3"); MessageBox.Show("a="+ a.ToString() + "\n" + "b=" + b.ToString() + "\n" + "stringList1.count=" + stringList1.Count.ToString() + "\n" + "stringList2.count=" + stringList2.Count.ToString() ); /* Output: a=a b=b stringList1.count=6 stringList2.count=6 */ |
Het punt is dus dat er een referentie wordt gelegd naar intList zodra intList2 wordt aangemaakt, maar hoe kan ik nu voorspellen dat er een referentie wordt gemaakt, en geen kopie zoals bij de Strings? M.a.w. hoe weet ik of iets een value type is of een reference type is? Dus hoe weet ik dat ik een copy/clone moet maken?