C#接口之谈
首先声明一点,我是个编程初学者,同时也是一个视编程如艺术的追求者,这篇博文是我课余时间撰写的,鄙人水平有限,但我还是想把我对接口的理解说出来,仅希望能给一些尚未了解它的人的一丝指引,首次写博文,希望大家能谅解我的不足并给予指正。
接口的概念及声明
1.接口是一种用来定义程序的协议。
2.接口可以是命名空间或类的成员,并且可以包含下列成员的签名:方法、属性、索引器、事件。
3.接口可以继承其它一个或多个接口,一个类可以继承或实现多个接口。
4.实现接口的非抽象类必须实现其内部声明的成员。
5.不能显示给接口成员赋予访问修饰符,所有接口成员的默认访问类型都是public。
6.实现接口的类可以显式实现该接口的成员。显式实现的成员不能通过类实例访问,而只能通过接口实例访问。
对接口的理解
1.接口中所有成员都是虚的,为什么说是虚的呢,因为接口内部只包含成员的声明部分,具体怎么实现都不是接口要关心的,它只是作为一种规范存在。
2 接口的作用,简而概之,就是标志类的类别。把不同类型的类归于不同的接口,可以更好的管理他们。面向对象的的精髓,是将对象的进一步抽象,最能体现这一点的就是接口。
3.我们在做项目时经常会用到三层架构的思想,假如在BLL层定义了类A,在DAL层定义了类B,在类A中实例化类B的一个对象,并通过该对象完成操作。显然,如果希望换一种数据访问方式,很有可能要修改BLL层的代码,因为在类A中实例化了类B的一个对象。如果使用接口,上层类就不能直接依赖下层类,而只依赖下层提供的一个接口,这就满足了“松散耦合”的设计理念。
现在请允许我写个例子来进一步探讨
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace InterfaceTest 7 { 8 public interface Animal //定义Animal接口 9 { 10 void eat(); //声明eat方法 11 void drink(); 12 } 13 14 public class dog :Animal //定义dog类,其实现Animal接口 15 { 16 public void eat() //实现eat方法 17 { 18 Console.WriteLine("Dogs eat bones"); 19 } 20 public void drink() 21 { 22 Console.WriteLine("The dog drink"); 23 } 24 } 25 26 class Program 27 { 28 static void Main(string[] args) 29 { 30 dog mydog = new dog(); //实例化dog类 31 mydog.eat(); //mydog对象调用eat方法 32 mydog.drink(); //mydog对象调用drink方法 33 } 34 } 35 }
我写上面那个小例子的意图是想说明一点:实现接口的非抽象类,必须实现该接口的所有成员。
单继承我想大家都应该很容易就理解了,但是我想着重说下多继承,如果类实现两个接口,并且这两个接口包含具有相同签名的成员,那么在类中实现该成员将导致两个接口都使用该成员作为它们的实现。例如:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace InterfaceTest 7 { 8 interface Itest1 9 { 10 void fun(); 11 } 12 interface Itest2 13 { 14 void fun(); 15 } 16 class test : Itest1, Itest2 17 { 18 //Itest1.fun和Itest1.fun都调用这个方法 19 public void fun() 20 { 21 Console.WriteLine("这两个接口包含具有相同签名的成员"); 22 } 23 } 24 class Program 25 { 26 static void Main(string[] args) 27 { 28 29 } 30 } 31 }
但是,如果两个接口成员执行不同的操作,这就有可能导致其中一个接口的实现不正确或两个接口的实现都不正确。这就有了显式地实现接口成员。这是使用接口名称和一个英文句点命名该类成员来实现的。例如:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace InterfaceTest 7 { 8 interface Itest1 9 { 10 void fun(); 11 } 12 interface Itest2 13 { 14 void fun(); 15 } 16 class test : Itest1, Itest2 17 { 18 void Itest1.fun() 19 { 20 Console.WriteLine("执行操作A"); 21 } 22 void Itest2.fun() 23 { 24 Console.WriteLine("执行操作B"); 25 } 26 } 27 class Program 28 { 29 static void Main(string[] args) 30 { 31 test mytest = new test(); 32 Itest1 myItest1 = (Itest1)mytest; 33 myItest1.fun(); 34 Itest2 myItest2 = (Itest2)mytest; 35 myItest2.fun(); 36 } 37 } 38 }
正如上面代码所明确的,类成员 Itest1.fun 只能通过 Itest1 接口使用,而Itest2.fun() 只能通过 Itest2 使用。这两个方法是分别实现的,并且两者都不可以直接在类中使用。
好吧就到这里了,我知道还有很多关于接口的问题尚未提及,但是我的水平的确很次,第一次出来献献丑,不伤大雅.......