什么是代表们的优势是什么? [英] What are the advantages of delegates?

查看:241
本文介绍了什么是代表们的优势是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是使用委托的好处/优点?任何人都可以提供任何简单的例子?

What are the benefits/advantages of using delegates? Can anyone provide any simple examples?

推荐答案

他们是封装了一块code的好方法。例如,当您将事件处理程序的按钮,该处理程序为代表。该按钮并不需要知道它做什么,只是如何在合适的时间调用它。

They're a great way of encapsulating a piece of code. For instance, when you attach an event handler to the button, that handler is a delegate. The button doesn't need to know what it does, just how to call it at the right time.

另一个例子是LINQ - 过滤,投影等,都需要同样的模板code;所有的改变是逻辑重新present过滤器,投影等,在C#3拉姆达EX pressions(被转换成代表或前pression树)这使得它非常简单:

Another example is LINQ - filtering, projecting etc all require the same kind of template code; all that changes is the logic to represent the filter, the projection etc. With lambda expressions in C# 3 (which are converted into delegates or expression trees) this makes it really simple:

var namesOfAdults = people.Where(person => person.Age >= 18)
                          .Select(person => person.Name);

(这也可以被重新psented作为查询EX pression $ P $,但我们不要从代表太远。)

(That can also be represented as a query expression, but let's not stray too far from delegates.)

委托的思维的另一方式是作为单方法接口类型。例如,事件处理程序委托类型有点像:

Another way of thinking of a delegate is as a single-method interface type. For example, the EventHandler delegate type is a bit like:

public interface IEventHandler
{
    void Invoke(object sender, EventArgs e)
}

但在框架的委托支持允许代表链接在一起,异步调用,作为事件处理程序等。

But the delegate support in the framework allows delegates to be chained together, invoked asynchronously, used as event handlers etc.

更多关于委托和事件,请参见我的话题的文章。其重点是事件,但它涵盖的代表了。

For more on delegates and events, see my article on the topic. Its focus is events, but it covers delegates too.

这篇关于什么是代表们的优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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