差异通过委托和事件C#调用 [英] Difference in invoking through Delegates and Events C#

查看:115
本文介绍了差异通过委托和事件C#调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别?

使用代表

public delegate void TestDelegate();
public TestDelegate delObj = SomeMethod;

public void SomeMethod()
{
    .....
}

public void Test()
{
    if(delObj != null)
        delObj();
}



使用事件

public delegate void TestDelegate();
public event TestDelegate EdelObj += SomeMethod;

public void SomeMethod()
{
    .....
}

public void Test()
{
    if(EdelObj != null)
        EdelObj();
}



似乎都工作。任何人都可以解释的区别是什么,我们应该使用哪种情况上述之一?

Both seem to work. Can anybody explain what is the difference and which scenario should we use one of the above?

编辑
链两个作品。对不起,这是从我的目的是错误的。

Edit Chaining works for both. Sorry it was a mistake from my end.

由于
NISHANT

Thanks Nishant

推荐答案

这是事件的声明实际上只是一种特殊的属性,它是用来揭露委托。而不是get和set访问,不过,它创建添加和删除的。通常情况下,它们会自动实现,但如果你希望你可以添加自定义的行为:

An event declaration is really just a special kind of property that's used to expose a delegate. Instead of get and set accessors, though, it creates add and remove ones. Normally they're implemented automatically, but if you desire you can add custom behavior:

private MyEventHandler handler;
public event MyEventHandler MyEvent {
    add {
        handler += value;
        Trace.WriteLine("MyEvent handler attached.");
    }
    remove {
        handler -= value;
        Trace.WriteLine("MyEvent handler removed.");
    }
}

这做了两件事。首先,由于事件是它们可以被包括在接口的属性。其次,由于MyEvent没有返回值,则委托完全封装,只拥有它可以调用它的对象。暴露代表的其他方式造成,可以通过几乎任何人都可以调用的委托。

This does two things. First, since events are properties they can be included in interfaces. Second, since MyEvent does not return a value, the delegate is completely encapsulated and only the object that owns it can invoke it. Other ways of exposing delegates result in a delegate that can be invoked by just about anyone.

除了特殊的语言支持位,事件和代表之间的另一个主要区别是一个约定,而不是语言或框架的功能:预计活动遵循某些模式,如确保在该事件是基于委托遵循的的事件处理代表。

Beyond that bit of special language support, the other major difference between events and delegates is a convention rather than a language or framework feature: Events are expected to follow certain patterns, such as making sure that the delegate on which the event is based follows the pattern established by the EventHandler delegate.

一般情况下,只要语义事件是首选的对象,通知任何人谁的兴趣有关的阶段的变化。代表们最好在你希望别人能够通过提供自己的方法,如采取由许多与在LINQ上使用IEnumerable的扩展方法委托参数来定义行为的情况。

Generally, events are preferred whenever the semantics are that of an object notifying anyone who's interested about a change in its stage. Delegates are preferred in situations where you want others to be able to define behavior by supplying their own procedure, such as the delegate parameters that are taken by many of the extension methods on IEnumerable that are used in LINQ.

这篇关于差异通过委托和事件C#调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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