計算機科学のブログ

reading and writing files - Save the last byte for me! - StreamWriter, WriteLine method

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 10(reading and writing files - Save the last byte for me!)、p.535(StreamWriter Magnets)の解答を求めてみる。

コード

Program.cs

using ConsoleApp1;

Flobbo flobbo = new Flobbo("blue yellow");
StreamWriter streamWriter = Flobbo.Snobbo();
flobbo.Blobbo(flobbo.Blobbo(flobbo.Blobbo(streamWriter),
                            streamWriter),
              streamWriter);

Flobbo.cs

using System;

namespace ConsoleApp1;

public class Flobbo(string zap)
{
    private string zap = zap;

    public static StreamWriter Snobbo()
    {
        return new StreamWriter("macaw.txt");
    }
    public bool Blobbo(StreamWriter sw)
    {
        sw.WriteLine(zap);
        zap = "green purple";
        return false;
    }
    public bool Blobbo(bool Already, StreamWriter sw)
    {
        if (Already)
        {
            sw.WriteLine(zap);
            sw.Close();
            return false;
        }
        else
        {
            sw.WriteLine(zap);
            zap = "red orange";
            return true;
        }
    }
}

入出力結果(Terminal, Zsh)

% dotnet run
% ls                              
ConsoleApp1.csproj	Program.cs		obj
ConsoleApp1.sln		bin
Flobbo.cs		macaw.txt
% cat macaw.txt 
blue yellow
green purple
red orange
%