C# 代表的优势是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/639320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the advantages of delegates?
提问by Xaisoft
What are the benefits/advantages of using delegates? Can anyone provide any simple examples?
使用委托的好处/优势是什么?谁能提供任何简单的例子?
采纳答案by Jon Skeet
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.
它们是封装一段代码的好方法。例如,当您将事件处理程序附加到按钮时,该处理程序就是一个委托。按钮不需要知道它做什么,只需要知道如何在正确的时间调用它。
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:
另一个例子是 LINQ——过滤、投影等都需要相同类型的模板代码;所有的变化都是表示过滤器、投影等的逻辑。使用 C# 3 中的 lambda 表达式(转换为委托或表达式树)这使它变得非常简单:
var namesOfAdults = people.Where(person => person.Age >= 18)
.Select(person => person.Name);
(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:
另一种将委托视为单方法接口类型的方式。例如,EventHandler
委托类型有点像:
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.
有关代表和事件的更多信息,请参阅我关于该主题的文章。它的重点是事件,但它也涵盖了代表。
回答by Joshua
Delegate in C# is eqv. to function pointer in C, but it also carries a reference to the class instance that it was created from.
C# 中的委托是 eqv。到 C 中的函数指针,但它也携带对创建它的类实例的引用。
All event handlers in Windows Forms are delegates.
Windows 窗体中的所有事件处理程序都是委托。
回答by Noldorin
Advantages compared to what? Delegates can be useful things, and surely have their place in a lot of moderately complex C# code. (Whenever you use events in classes you are implicitly using multicast delegates). If you want an introduction to their syntax and uses, I recommend the following articles:
相比什么优势?委托可以是有用的东西,并且肯定在许多中等复杂的 C# 代码中占有一席之地。(每当您在类中使用事件时,您都在隐式使用多播委托)。如果你想了解它们的语法和用途,我推荐以下文章:
回答by Michael Meadows
Delegates serve three purposes:
代表有三个目的:
- A simplified implementation of the Observer pattern
- A simplified implementation of callbacks
- Anonymous (non-reusable) blocks of code
- 观察者模式的简化实现
- 回调的简化实现
- 匿名(不可重用)代码块
Observer
观察员
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
}
}
CallBack
打回来
public void DoSomethingAsynchronously(EventHandler callBack)
{
// long running logic.
callBack(this, EventArgs.Empty);
}
Anonymous non-reusable code
匿名不可重用代码
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 */ });
}
In all cases, it's just a matter of providing conciceness.
在所有情况下,这只是提供conciceness 的问题。
回答by Reed Copsey
This is a pretty vague topic, but here are a few things to consider -
这是一个相当模糊的话题,但这里有一些事情需要考虑——
Delegates are basically a cleaner, easier function pointer. Any place where function pointers were used in C++, you can think delegate.
委托基本上是一个更干净、更简单的函数指针。任何在 C++ 中使用函数指针的地方,你都可以认为是委托。
Advantages to using them in design:
在设计中使用它们的优势:
- Can lead to easy reuse of code
- Can provide a great amount of flexibility in your designs
- Allow you to develop libraries and classes that are easily extensible, since it provides an easy way to hook in other functionality (for example, a where clause in LINQ can use a delegate
[Func<T,bool>]
to filter on, without having to write new code in the Where method
- 可以轻松重用代码
- 可以为您的设计提供极大的灵活性
- 允许您开发易于扩展的库和类,因为它提供了一种挂接其他功能的简单方法(例如,LINQ 中的 where 子句可以使用委托
[Func<T,bool>]
进行过滤,而无需在 Where 方法中编写新代码
Potential disadvantages:
潜在的缺点:
- They
~can~
, particularly if used naively, lead to code that is more difficult to read - They can introduce behavior into your component that is unexpected, since 3rd party code out of your control will get called (For example, if somebody attaches a delegate to one of your events that causes an infinite loop, it can make your class look bad, even though it has nothing to do with you)
- 它们
~can~
,特别是如果天真地使用,会导致代码更难阅读 - 它们可能会在您的组件中引入意想不到的行为,因为您无法控制的第 3 方代码将被调用(例如,如果有人将委托附加到导致无限循环的事件之一,它会使您的类看起来很糟糕,即使它与你无关)
回答by Jeff Keslinke
Disclaimer: I'm not saying how I used a delegate is the intended way but it is an example.
免责声明:我并不是说我如何使用委托是预期的方式,但它是一个例子。
I've only used it once before but basically in our app the user clicks a 'Complete' button for a step which then takes them to a routing page to decide where to send it next. So technically the step they just clicked 'Complete' on isn't really finished until they route it. But since I'm on another page I didn't easily have access to where they just were.
我之前只使用过一次,但基本上在我们的应用程序中,用户单击“完成”按钮执行一个步骤,然后将他们带到路由页面以决定下一步将其发送到哪里。所以从技术上讲,他们刚刚点击“完成”的步骤在他们路由之前并没有真正完成。但是由于我在另一个页面上,因此我无法轻松访问它们所在的位置。
So what I did was created a delegate for the few steps that required special processing (in this case an email) when the clicked 'Complete', and when they routed it on the next page I would check for the existance of the delegate and if it was there call it to fire my 'stored' event.
因此,我所做的是在单击“完成”时为需要特殊处理的几个步骤(在本例中为电子邮件)创建了一个委托,当他们将其路由到下一页时,我将检查委托是否存在它在那里调用它来触发我的“存储”事件。
Creative: probably, wrong: maybe, working: definately.
创意:可能,错误:可能,工作:肯定。
Like I said probably not how it was intended to be used, but coding is as much art as science right?
就像我说的可能不是它的用途,但是编码既是科学又是艺术,对吧?
回答by Anthony
I remember an early Java GUI framework that had no concept of delegates or command routing. In order to make a button that does something, you had to subclass Buttonand override the click method. You ended up with lots and lots of UI element subclasses with little bits of your application code in them.
我记得早期的 Java GUI 框架没有委托或命令路由的概念。为了制作一个可以执行某些操作的按钮,您必须子类化 Button并覆盖 click 方法。您最终得到了大量 UI 元素子类,其中包含少量应用程序代码。
The code that handles that click has to go somewhere, and in an OO language like Java or C# it has to go on a class, but delegates allow it to happen on convenient place. That often leads to having too much code doing too many different things in a form class, but that's a different issue.
处理点击的代码必须放在某个地方,在像 Java 或 C# 这样的 OO 语言中,它必须放在一个类上,但委托允许它发生在方便的地方。这通常会导致有太多代码在一个表单类中做太多不同的事情,但这是一个不同的问题。