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

查看:25
本文介绍了通过委托和事件 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.

谢谢尼桑特

推荐答案

事件声明实际上只是一种用于公开委托的特殊属性.但是,它不是 get 和 set 访问器,而是创建 add 和 remove 访问器.通常它们是自动实现的,但如果您愿意,您可以添加自定义行为:

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.

除了那一点特殊的语言支持之外,事件和委托之间的另一个主要区别是约定而不是语言或框架功能:预计事件将遵循 某些模式,例如确保事件所基于的委托遵循 EventHandler 委托.

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天全站免登陆