接口
对实现了对某接口的类的实例进行访问时,可以直接访问,还可以通过接口实例来访问。
下面的代码演示通过接口实例访问实现了某接口的类的实例
namespace JieKou { interface Ifunction1 { int sum(int x1, int x2); } interface Ifunction2 { string str { get;set;} } class MyTest:Ifunction1,Ifunction2 { private string mystr; public MyTest() { } public MyTest(string str) { mystr=str; } public int sum(int x1, int x2) { return x1 + x2; } public string str { get { return mystr; } set { mystr = value; } } } class Program { static void Main(string[] args) { MyTest a = new MyTest(); Console.WriteLine(a.sum(10,20)); MyTest b = new MyTest("How are you"); Console.WriteLine(b.str); Ifunction1 c = new MyTest(); Console.WriteLine(c.sum(20,30)); Ifunction2 d = new MyTest("How do you do"); Console.WriteLine(d.str); Console.ReadKey(); } } }
接口不能直接实例化,但可以入如上所示,接口实例用接口Ifunction来声明,用实现类MyTest来实例化。因此,可以如同上例一样使用接口实例c的方法sum。

浙公网安备 33010602011771号