实现接口的好处 [英] Benefits of implementing an interface

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

问题描述

什么是实现接口的好处C#3.5?

what are the benefits of implementing an interface in C# 3.5 ?

推荐答案

您就可以将你的对象传递给一个方法(或满足类型约束)的预期接口作为参数。 C#不支持鸭打字。只是写由接口定义的方法,对象将不会自动成为兼容接口类型:

You'll be able to pass your object to a method (or satisfy a type constraint) that expects the interface as an argument. C# does not support "duck typing." Just by writing the methods defined by the interface, the object will not automatically be "compatible" with the interface type:

public void PrintCollection<T>(IEnumerable<T> collection) {
    foreach (var x in collection)
       Console.WriteLine(x);
}

如果列表< T> 没有实现的IEnumerable< T> 界面,你将无法把它作为参数传递给 PrintCollection 办法(即使它有一个的GetEnumerator 法)。

If List<T> did not implement the IEnumerable<T> interface, you wouldn't be able to pass it as an argument to PrintCollection method (even if it had a GetEnumerator method).

基本上,一个接口声明的合同。实现接口(通过提供适当的成员)强制执行类绑定到了合同。因此,依赖该合同(即依赖于由您的对象提供的接口规定的功能性的方法)的一切可以用你的对象工作过。

Basically, an interface declares a contract. Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.

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

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