CAPTAIN AMAZING - THE DEATH OF THE OBJECT - extension methods, fundamental types, int, bool, string
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 11(CAPTAIN AMAZING - THE DEATH OF THE OBJECT)、p.620(Extension Magnets)の解答を求めてみる。
コード
Program.cs
namespace Sideways
{
using Upside;
class Program
{
static void Main(string[] args)
{
int i = 1;
bool b = true;
string s = i.ToPrice();
i.ToPrice().SendIt();
b.Green().SendIt();
b = false;
b.Green().SendIt();
i = 3;
i.ToPrice().SendIt();
}
}
}
Margin.cs
namespace Upside;
public static class Margin
{
public static void SendIt(this string s)
{
Console.Write(s);
}
public static string ToPrice(this int n)
{
if (n == 1)
{
return "a buck ";
}
return " more bucks";
}
public static string Green(this bool b)
{
if (b)
{
return "be";
}
return "gets";
}
}
入出力結果(Terminal, Zsh)
% dotnet run
a buck begets more bucks%