上級 › does not contain a definition の原因と直し方(明示的インターフェース実装) › パターン3
does not contain a definition の原因と直し方(明示的インターフェース実装)
明示的インターフェース実装(void IWorker.Work()のような書き方)で定義したメンバーは、クラス型の変数からは見えません。
1 interface IPrinter { void Print(); } 2 class Report : IPrinter { 3 void IPrinter.Print() { System.Console.WriteLine("Printing"); } 4 } 5 class Program { 6 static void Main(string[] args) { 7 ________ r = new Report(); ^ 8 r.Print(); 9 } 10 }
Program.cs(8,11): error CS1061: 'Report' does not contain a definition for 'Print' and no accessible extension method 'Print' accepting a first argument of type 'Report' could be found (are you missing a using directive or an assembly reference?)
空欄を埋めてビルドを通す
同じ理由で、Report型の変数からPrintは呼べません。複数のインターフェースで同名メソッドが衝突する場合によく使うテクニックです。
次の問題