インタフェースを用意した。
成果物
前回
インタフェースとして実装を強いるメソッドが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()
で呼び出せる。
対象環境
- Raspbierry pi 3 Model B+
- Raspbian stretch 9.0 2018-11-13 ※
- bash 4.4.12(1)-release ※
- SQLite 3.29.0 ※
- C# dotnet 3.0.100
$ uname -a Linux raspberrypi 4.19.42-v7+ #1218 SMP Tue May 14 00:48:17 BST 2019 armv7l GNU/Linux