配列が参照型というのは、配列を格納する変数が参照型ということです。
今回の例で言うと、a,b,cです。
そして、配列の要素はどうなのかというと型によります。
今回の例ですと、int型なので値型となります。
構成する要素が参照型であれば、参照型として動きます。
ただし、string型は参照型ですが、ちょっと特殊で値型と同じ動きをします。
C#
1class Hoge
2{
3 public static void Main()
4 {
5 //要素が値型の配列
6 int[] a = { 1, 2 };
7 int[] b = new int[a.Length];
8 int[] c = { 3, 4 };
9
10 b = a;
11 c[0] = a[0];
12 a[0] = 10;
13
14 Console.WriteLine(b[0]); // 10
15 Console.WriteLine(c[0]); // 1
16
17 //要素が参照型の配列
18 TestClass[] aa = { new TestClass(1), new TestClass(2) };
19 TestClass[] bb = new TestClass[aa.Length];
20 TestClass[] cc = { new TestClass(3), new TestClass(4) };
21
22 bb = aa;
23 cc[0] = aa[0];
24 aa[0].ValueA = 10;
25
26 Console.WriteLine(bb[0].ValueA); // 10
27 Console.WriteLine(cc[0].ValueA); // 10
28
29
30 //要素が参照型の配列(string)
31 string[] aaa = { "1", "2" };
32 string[] bbb = new string[aaa.Length];
33 string[] ccc = { "3", "4" };
34
35 bbb = aaa;
36 ccc[0] = aaa[0];
37 aaa[0] = "10";
38
39 Console.WriteLine(bbb[0]); // "10"
40 Console.WriteLine(ccc[0]); // "1"
41 }
42}
43
44public class TestClass
45{
46 public int ValueA;
47 public TestClass(int value) { ValueA = value; }
48}
49
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/24 08:44