传递接口而不是对象实例 [英] Passing an interface instead of an object instance

查看:134
本文介绍了传递接口而不是对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以SqlBulkCopy.WriteToServer()方法为例。其中一个重载采用IDataReader作为参数。我的问题是,将接口传递给方法而不是对象实例本身有什么好处/好处?

Take for instance the SqlBulkCopy.WriteToServer() method. One of the overloads takes an IDataReader as the parameter. My question is, what's the benefit/advantage to passing an interface to a method instead of the object instance itself?

http://msdn.microsoft.com/en-us/library/434atets.aspx

推荐答案

您可以为该一个接口提供许多可能的实现。它更好地依赖于抽象(在这种情况下是一个接口)而不是实际的具体类 - 这允许更好的灵活性和可测试性。

You can have many possible implementations for that one interface. Its better to depend on an abstraction (in this case an interface) than an actual concrete class - this allows much better flexibility and testability.

这也将重点放在什么上 WriteToServer()方法确实需要 - 它的合同唯一需要的是调用者传入具体类的任何实例提供 IDataReader 接口声明的方法/属性。

This also puts the focus on what is really required by the WriteToServer() method - the only thing its contract requires is for the caller to pass in any instance of a concrete class that provides the methods / properties declared by the IDataReader interface.

这篇关于传递接口而不是对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆