やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

C#8.0のインタフェース新機能を試してみる2

 インタフェースを用意した。

成果物

前回

 インタフェースとして実装を強いるメソッドが1つもないのはおかしい。

コード

IBot.cs

public interface IBot
{
    public string Generate();
    protected static string DefaultGenerate() => "デフォルトのtootです。";
}

DefaultBot.cs

public class DefaultBot : IBot
{
    public string Generate() => IBot.DefaultGenerate();
}

FixedBot.cs

public class FixedBot : IBot
{
    public string Generate() => "これは固定tootです。";
}

DateTimeBot.cs

public class DateTimeBot : IBot
{
    public string Generate() => $"これは{DateTime.Now:yyyy-MM-dd HH:mm:ss}時点におけるtootです。";
}

GreetingBot.cs

public class GreetingBot : IBot
{
    public string Generate() => DateTime.Now.Hour switch 
    {
        int n when (3 < n && n < 10) => "おはようございます。",
        int n when (9 < n && n < 17) => "こんにちは。",
        int _ => "こんばんは。",
    };
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(new DefaultBot().Generate());
        Console.WriteLine(new FixedBot().Generate());
        Console.WriteLine(new DateTimeBot().Generate());
        Console.WriteLine(new GreetingBot().Generate());
    }
}

所感

 これでIBotインタフェースを継承したらGenerateメソッドをオーバーライドを強いることができる。もし継承しているのに未実装ならコンパイルエラーになる。

 デフォルト処理を使いたくばIBot.DefaultGenerate()で呼び出せる。

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1218 SMP Tue May 14 00:48:17 BST 2019 armv7l GNU/Linux