計算機科学のブログ

data, types, objects, and references - Managing your app's data - instances, swap the reference values

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.230(Exercise)の解答を求めてみる。

コード

Program.cs


using ConsoleApp3;

Console.WriteLine("Press 1 for Lloyd, 2 for Lucinda, 3 to swap");
Elephant lucinda = new Elephant() { Name = "Lucinda", EarSize = 33 };
Elephant lloyd = new Elephant() { Name = "Lloyd", EarSize = 40 };

while (true)
{
    char keyChar = Console.ReadKey(true).KeyChar;
    if (keyChar == '1')
    {
        Console.WriteLine("You pressed 1");
        Console.WriteLine("Calling lloyd.WhoAmI()");
        lloyd.WhoAmI();
    }
    else if (keyChar == '2')
    {
        Console.WriteLine("You pressed 2");
        Console.WriteLine("Calling lucinda.WhoAmI()");
        lucinda.WhoAmI();
    }
    else if (keyChar == '3')
    {
        Console.WriteLine("You pressed 3");
        Console.WriteLine("References have been swapped");
        Elephant t = lucinda;
        lucinda = lloyd;
        lloyd = t;
    }
    else
    {
        break;
    }
    Console.WriteLine();
}

Elephant.cs

namespace ConsoleApp3;

public class Elephant
{
    public string Name = "";
    public int EarSize;

    public void WhoAmI()
    {
        Console.WriteLine($"My name is {Name}.");
        Console.WriteLine($"My ears are {EarSize} inches tall..");
    }
}

入出力結果(Terminal, Zsh)

% dotnet run
Press 1 for Lloyd, 2 for Lucinda, 3 to swap
You pressed 1
Calling lloyd.WhoAmI()
My name is Lloyd.
My ears are 40 inches tall..

You pressed 2
Calling lucinda.WhoAmI()
My name is Lucinda.
My ears are 33 inches tall..

You pressed 3
References have been swapped

You pressed 1
Calling lloyd.WhoAmI()
My name is Lucinda.
My ears are 33 inches tall..

You pressed 2
Calling lucinda.WhoAmI()
My name is Lloyd.
My ears are 40 inches tall..

You pressed 3
References have been swapped

You pressed 1
Calling lloyd.WhoAmI()
My name is Lloyd.
My ears are 40 inches tall..

You pressed 2
Calling lucinda.WhoAmI()
My name is Lucinda.
My ears are 33 inches tall..

%