C#8.0からインターフェースでメソッドの実装ができるようなので試してみた。
はじめに
C#のお勉強としてのんびりrksoftwareさんのC#関連の記事を読んでいたらC#8.0からインターフェースでもメソッドの実装が出来るようになったことを知ったので実際に試してみました。 勉強になりました!ありがとうございます!
サンプルコード
実際にインターフェースでメソッドの実装をしてみましょう。
継承先で実装をしない場合
インターフェースを継承のみしたクラスで型定義を行うとコンパイルエラーになりますが、インターフェースの型で定義を行った場合はコンパイルが通ります。
class Program { static void Main(string[] args) { Sample sample = new Sample(); sample.Paint(); //コンパイルエラー IExistsImplement iSample = new Sample(); iSample.Paint(); //出力 --> "Default Paint method" } } public class Sample : IExistsImplement { } interface IExistsImplement { void Paint() => Console.WriteLine("Default Paint method"); }
継承先で実装をした場合
インターフェースを継承したクラスでメソッドの実装を行った場合はクラスの型で定義してもインターフェースの型で定義してもクラスの実装が使われます。
class Program { static void Main(string[] args) { Sample sample = new Sample(); sample.Paint(); //出力 --> "Change Paint method" IExistsImplement iSample = new Sample(); iSample.Paint(); //出力 --> "Change Paint method" } } public class Sample : IExistsImplement { public void Paint() => Console.WriteLine("Change Paint method"); } interface IExistsImplement { void Paint() => Console.WriteLine("Default Paint method"); }