Jon*_*eet 44
它们是封装一段代码的好方法.例如,当您将事件处理程序附加到按钮时,该处理程序是委托.按钮不需要知道它的作用,只是如何在正确的时间调用它.
另一个例子是LINQ - 过滤,投影等都需要相同类型的模板代码; 所有这些变化都是表示过滤器,投影等的逻辑.使用C#3中的lambda表达式(转换为委托或表达式树),这使得它非常简单:
var namesOfAdults = people.Where(person => person.Age >= 18)
.Select(person => person.Name);
Run Code Online (Sandbox Code Playgroud)
(这也可以表示为查询表达式,但是我们不要偏离委托太远.)
另一种思考委托的方式是作为单方法接口类型.例如,EventHandler委托类型有点像:
public interface IEventHandler
{
void Invoke(object sender, EventArgs e)
}
Run Code Online (Sandbox Code Playgroud)
但是框架中的委托支持允许委托链接在一起,异步调用,用作事件处理程序等.
有关代理和事件的更多信息,请参阅我关于该主题的文章.它的重点是活动,但也包括代表.
Ree*_*sey 12
这是一个非常模糊的话题,但这里有几点需要考虑 -
代表基本上是一个更简洁,更容易的函数指针.在C++中使用函数指针的任何地方,你都可以认为是委托.
在设计中使用它们的优点:
[Func<T,bool>]进行过滤,而无需在Where方法中编写新代码潜在的缺点:
~can~,特别是如果天真地使用,会导致更难以阅读的代码代表们有三个目的:
观察
public class Something
{
public event EventHandler SomethingHappened;
}
public class SomethingConsumer
{
private mySomething = new Something();
public void WireUpEvents()
{
mySomething.SomethingHappened += whenSomethingHappened;
}
private void whenSoemthingHappened(object sender, EventArgs e)
{
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
打回来
public void DoSomethingAsynchronously(EventHandler callBack)
{
// long running logic.
callBack(this, EventArgs.Empty);
}
Run Code Online (Sandbox Code Playgroud)
匿名不可重用的代码
public void DoSomethingReusably(Action nonReusableCode)
{
// reusable code
nonReusableCode();
// more reusable code
}
public void DoALotOfSomething()
{
DoSomethingReusably(() => { /* non-reusable code here */ });
DoSomethingReusably(() => { /* non-reusable code here */ });
DoSomethingReusably(() => { /* non-reusable code here */ });
}
Run Code Online (Sandbox Code Playgroud)
在所有情况下,这只是提供简洁性的问题.