该篇文章是我于2009年6月10日通过自己编写的工具,批量从位于在博客园的博客站点(http://chenxizhang.cnblogs.com)同步而来。文章中的图片地址仍然是链接到博客园的。特此说明! 陈希章原文地址:http://www.cnblogs.com/chenxizhang/archive/2008/08/22/1274265.html原文标题:实现接口与显式实现接口的区别 原文发表:2008/8/22 9:05:00 |
在实现接口的时候,VS提供了两个菜单,一个是"实现接口",一个是"显式实现接口",它们到底有何不一样呢
我们来比较一下看看
1.首先假设我们有一个接口
public interface ICustomer
{
void SomeMethod();
}
2.如果是"实现接口",那么代码大致如下
public class Customer:ICustomer
{
#region ICustomer 成员
public void SomeMethod()
{
throw new NotImplementedException();
}
#endregion
}
3.如果是"显式实现接口",那么代码大致如下
public class Customer:ICustomer
{
#region ICustomer 成员
void ICustomer.SomeMethod()
{
throw new NotImplementedException();
}
#endregion
}
大家看到差别了吧?显式实现的方式,那些方法都会加上一个前缀的。但是,这到底意味着什么呢?
如果是实现接口
public class DAL {
///
/// 如果我们是直接实现接口的话,那么既可以用接口调用方法,也可以用具体类调用方法
///
public void GetCustomer() {
Customer customer = new Customer();
customer.SomeMethod();
}
public void GetCustomer2() {
ICustomer customer = new Customer();
customer.SomeMethod();
}
}
如果是显式实现接口
public class DAL {
///
/// 如果我们是显式实现接口的话,那么要访问里面的方法就只能是通过接口来调用,而不能通过具体类来做
///
public void GetCustomer() {
ICustomer customer = new Customer();
customer.SomeMethod();
}
}
现在大部分的系统为了保证扩展性,都广泛地使用接口。显式实现接口,可以隐藏具体类的复杂性。
作者:陈希章 出处:http://blog.csdn.net/chen_xizhang 本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |