When to Use Delegates Instead of Interfaces

本文探讨了在软件设计中使用委托与接口的区别。通过对比两者的特点,为开发者提供了选择依据。例如,在事件驱动的设计模式中更适合使用委托;而当一组相关的方法需要被调用时,则推荐采用接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method. Given these similarities, when should a class designer use a delegate and when should it use an interface?

Use a delegate in the following circumstances:

  • An eventing design pattern is used.

  • It is desirable to encapsulate a static method.

  • The caller has no need to access other properties, methods, or interfaces on the object implementing the method.

  • Easy composition is desired.

  • A class may need more than one implementation of the method.

Use an interface in the following circumstances:

  • There is a group of related methods that may be called.

  • A class only needs one implementation of the method.

  • The class using the interface will want to cast that interface to other interface or class types.

  • The method being implemented is linked to the type or identity of the class: for example, comparison methods.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值