Can I use interface method instead of delegate? How? I found searching that interface method is faster than using delegates. I would appreciate a simple code snippet.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
In theory, it's possible to accomplish everything done by delegates with interfaces (Java has no delegates, for instance) containing a single method. However, it makes the code more verbose and adds little benefit. Then again, it's possible to do everything without classes and possibly do it faster. That doesn't mean you should avoid using classes. Calling a delegate method might be marginally slower than calling an interface method. You shouldn't care about the micro-optimization. Use whatever fits your specific need.
The biggest advantage of using delegates instead of interfaces is that while a class can only provide one implementation for any given interface, it can create delegates for any number of different methods. For example, suppose rather than exposing a Click event, Button exposed a ClickRecipient property of type IButtonClickHandler, with one method "ButtonClick". A form with two buttons which should have different handlers would have to define a separate class to handle at least one of them, since the form itself would only be able to have one implementation of ButtonClick. By contrast, a Button event accepts a delegate for an EventHandler, and a form can create delegates for any number of EventHandler methods.
Note that using generics and "marker types", one could mitigate this problem significantly, by having a Button(Of T) have a ClickRecipientProperty of type IButtonClickHandler(Of T); a form could thus have a Button(Of FooButton) and a Button(Of BarButton) and provide different implementations for their interfaces. One could also have a ButtonConverter(Of T,U) wrapper class, which would implement IButtonClickHandler(Of T) and invoke IButtonClickHandler(Of U).ButtonClick.
Interfaces are good if the usage pattern will 99% of the time match what the interface is designed for (the remaining 1% of the time, one can create an intermediate wrapper class).
Refer Delegates Are Anonymous Interfaces by Mark Seemann
In the above article Mark Seemann mentions an example
Interface Approach
Delegate Approach