Advantages of using delegates?

2019-01-21 21:06发布

I'm looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I've heard that delegates can be used for this, but can't figure out why they would be preferred over plain old interfaces implemented on observers. So,

  • Why should I use delegates instead of defining my own interfaces and passing around references to objects implementing them?
  • Why might I want to avoid using delegates, and go with good ol'-fashioned interfaces?

14条回答
Bombasti
2楼-- · 2019-01-21 21:46

i think it is more related to syntatic sugar and a way to organize your code, a good use would be to handle several methods related to a common context which ones belong to a object or a static class.

it is not that you are forced to use them, you can programme sth with and without them, but maybe using them or not might affect how organized, readable and why not cool the code would be, maybe bum some lines in your code.

Every example given here is a good one where you could implement them, as someone said it, is just another feature in the language you can play with.

greetings

查看更多
等我变得足够好
3楼-- · 2019-01-21 21:48

Delegates are strong typing for function/method interfaces.

If your language takes the position that there should be strong typing, and that it has first-class functions (both of which C# does), then it would be inconsistent to not have delegates.

Consider any method that takes a delegate. If you didn't have a delegate, how would you pass something to it? And how would the the callee have any guarantees about its type?

查看更多
登录 后发表回答