我认为自己是 CSharp 的新手。我遇到过这段代码,但无法理解它的作用。
我没有在任何地方看到 EventHandler 等于委托(delegate)?那有什么作用?当然,下面是完整代码的摘录,因为我希望这足以让某人理解将事件处理程序等同于委托(delegate)的一般概念。谢谢。
public class xyz : ViewModelBase
{
protected EventHandler modelChanged = null;
public xyz ( int a, int b)
{
this.modelChanged =
delegate
{
// check for changes.
if (this.ChangesExist == false)
{
// set the flag
this.ChangesExist = true;
// append the title.
currentTitle += "*";
_changeTitle(currentTitle);
}
};
}
}
最佳答案
I have not seen enywhere that an EventHandler is equal to a delegate ?
public delegate void EventHandler(
Object sender,
EventArgs e
)
(为简单起见删除了属性。)
在这种情况下,您看到的是 anonymous method - 一种从“内联”代码块创建委托(delegate)的方法。 Lambda expressions是如今实现这一目标的更常见方式。 (在 C# 2 中引入了匿名方法;在 C# 3 中引入了 lambda 表达式。)lambda 表达式和匿名方法都可以转换为委托(delegate)实例;一些 lambda 表达式也可以转换为 expression trees用于需要分析表达式中的逻辑的代码。
如果您总体上对委托(delegate)相当陌生,您可能还想阅读我关于 delegates and events 的文章.
关于c# - 在 C# 中将 EventHandler 类型 var 等同于委托(delegate)意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18664681/