.net 接口说明 [英] .net Interface explanation

查看:22
本文介绍了.net 接口说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 .Net 中的接口定义了接口和继承它的类之间的契约.刚刚完成了一个大量使用数据访问层接口的项目,这让我开始思考...有什么大不了的?当我必须向 DAL 添加新方法时,我必须在接口中创建方法签名,并将其添加到继承接口的类中,当然还有将方法添加到 DAL,从而创建额外工作".界面有什么大不了的,为什么我要为自己创造额外的工作?

I understand that an interface in .Net defines a contract between the interface and a class that inherits it. Having just gotten done working on a project that made heavy use of an interface for the Data Access Layer, it got me thinking . . . whats the big deal? When I had to add a new method to the DAL, I had to create the method signature in the interface along with adding it to the class that inherited the interface, and of course the method to the DAL, thus creating "extra work". Whats the big deal about interfaces and why would I want to create extra work for myself?

推荐答案

接口有什么大不了的?

一旦你定义了契约,你就可以更换实现而不必担心破坏你的其余代码.

Once you define the contract, you can swap out implementations without worrying about breaking the rest of your code.

考虑在 .NET 中使用 List 的代码性能不佳的情况.如果您使用 List 的硬实现,则很有可能通过更改实现来破坏更多代码.

Consider the situation where you have poor performing code that is making use of a List<T> in .NET. If you use the hard implementation of List<T>, there's a good chance you're going to break more code by changing the implementation.

如果您使用 IListIEnumerable,您将能够将 List 交换为 LinkedList(或任何实现您选择的界面的东西)并在一个地方解决问题,而不必接触所有代码.

If you were using IList<T> or IEnumerable<T> you would be able to swap List<T> for LinkedList<T> (or anything implementing your chosen interface) and fix the issue in one spot rather than having to touch all of your code.

最后......它是关于多态.

In the end...it's about about Polymorphism.

这篇关于.net 接口说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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