計算機科学のブログ

data, types, objects, and references - Managing your app's data - Multiple references and their side effects

Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 4(data, types, objects, and references - Managing your app’s data)、p.227(Sharpen your pencil)の解答を求めてみる。

コード

Program.cs



// 1
using ConsoleApp2;

void p(List<Dog> dogs)
{
    Console.WriteLine(dogs.Count);
    for (int i = 0; i < dogs.Count; i++)
    {
        for (int j = i + 1; j < dogs.Count; j++)
        {
            if (i != j)
            {
                Console.WriteLine($"{i}, {j}: {dogs[i] == dogs[j]}");
            }
        }
    }
}
Dog rover = new Dog() { Breed = "Greyhound" };
Dog rinTinTin = new Dog();
Dog fido = new Dog();
Dog bear = fido;
// (rover), (rinTinTin), (fido, bear)
List<Dog> dogs = [rover, rinTinTin, fido, bear];
p(dogs);


// Objects: 3
// references: 4

// 2
Dog spot = new Dog() { Breed = "Dachshund" };
spot = rover;
// (rover, spot), (rinTinTin), (fido, bear)
dogs.Add(spot);

// Objects: 3
// references 5
p(dogs);

// 3
Dog lucky = new Dog() { Breed = "Beagle" };
Dog charlie = fido;
fido = rover;
// (rover, spot, fido), (rinTinTin), (bear, charlie), (lucky)
dogs.Add(lucky);
dogs.Add(charlie);

// Objects: 4
// references 7
p(dogs);

// 4
rinTinTin = lucky;
Dog laverne = new Dog() { Breed = "pug" };
// (rover, spot, fido), (bear, charlie), (lucky, rinTinTin), (laverne)
dogs.Add(laverne);

// Objcts: 4
// references: 8
p(dogs);

// 5
charlie = laverne;
lucky = rinTinTin;
// (rover, spot, fido), (bear), (lucky, rinTinTin), (laverne, charlie)

// Objects: 4
// references: 8

Dog.cs

using System;

namespace ConsoleApp2;

public class Dog
{
    public string Breed = "";
}

入出力結果(Terminal, Zsh)

% dotnet run
4
0, 1: False
0, 2: False
0, 3: False
1, 2: False
1, 3: False
2, 3: True
5
0, 1: False
0, 2: False
0, 3: False
0, 4: True
1, 2: False
1, 3: False
1, 4: False
2, 3: True
2, 4: False
3, 4: False
7
0, 1: False
0, 2: False
0, 3: False
0, 4: True
0, 5: False
0, 6: False
1, 2: False
1, 3: False
1, 4: False
1, 5: False
1, 6: False
2, 3: True
2, 4: False
2, 5: False
2, 6: True
3, 4: False
3, 5: False
3, 6: True
4, 5: False
4, 6: False
5, 6: False
8
0, 1: False
0, 2: False
0, 3: False
0, 4: True
0, 5: False
0, 6: False
0, 7: False
1, 2: False
1, 3: False
1, 4: False
1, 5: False
1, 6: False
1, 7: False
2, 3: True
2, 4: False
2, 5: False
2, 6: True
2, 7: False
3, 4: False
3, 5: False
3, 6: True
3, 7: False
4, 5: False
4, 6: False
4, 7: False
5, 6: False
5, 7: False
6, 7: False
%