namespaces and classes - Organizing your code - An instance uses fields to keep track of things
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 3(namespaces and classes - Organizing your code)、p.167(Sharpen your pencil)の解答を求めてみる。
コード
Program.cs
using Clown;
Clown.Clown oneClown = new Clown.Clown();
oneClown.Name = "Boffo";
oneClown.Height = 14;
// My name is Boffo and I'm 14 inches tall.
oneClown.WhoAreYou();
Clown.Clown anotherClown = new Clown.Clown();
anotherClown.Name = "Biff";
anotherClown.Height = 16;
// My name is Biff and I'm 16 inches tall.
anotherClown.WhoAreYou();
Clown.Clown clown3 = new Clown.Clown();
clown3.Name = anotherClown.Name;
clown3.Height = oneClown.Height - 3;
// My name is Biff and I'm 11 tall.
clown3.WhoAreYou();
anotherClown.Height *= 2;
// My name is Biff and I'm 32 tall.
anotherClown.WhoAreYou();
コード
Clown.cs
namespace Clown;
class Clown
{
public string? Name;
public int Height;
public void WhoAreYou()
{
Console.WriteLine(
$"My name is {Name} ande I'm {Height} inches tall.");
}
}
入出力結果(Terminal, Zsh)
% dotnet run
My name is Boffo ande I'm 14 inches tall.
My name is Biff ande I'm 16 inches tall.
My name is Biff ande I'm 11 inches tall.
My name is Biff ande I'm 32 inches tall.
%