How can a delegate & interface be used interchange

2019-03-02 06:48发布

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.

3条回答
乱世女痞
2楼-- · 2019-03-02 07:28

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.

查看更多
Ridiculous、
3楼-- · 2019-03-02 07:29

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).

查看更多
趁早两清
4楼-- · 2019-03-02 07:43

Refer Delegates Are Anonymous Interfaces by Mark Seemann

In the above article Mark Seemann mentions an example

Interface Approach

public interface IMyInterface
{
    int DoIt(string message);
}
public string DoStuff(IMyInterface strategy)
{
    return strategy.DoIt("Ploeh").ToString();
}

Delegate Approach

public string DoStuff(Func<string, int> strategy)
{
    return strategy("Ploeh").ToString();
}
查看更多
登录 后发表回答