Onece a class implementation a particular interface, you can interact with the members of the interface through any instance of that class.
1 Cow bossie = new Cow("Bossie", 5); 2 3 // Cow implements IMoo, which includes Moo method 4 bossie.Moo();
You can also declare a variable whose type is an interface, assign it to an instance of any class that implements that interface and then interact with members of the interface through that interface variable.
1 // bossie is a Cow, which implements IMoo, so we can point IMoo variable at her 2 IMoo mooer = bossie; 3 mooer.Moo();
Notice that we can't access members of Cow that aren't part of IMoo using this interface variable.
1 // Can't call Cow methods not in IMoo 2 mooer.MakeSomeMilk();
Even though MakeSomeMilk is a public method in the Cow class, we can't access it via IMoo.
原文地址:#437 – Access Interface Members through an Interface Variable