简体   繁体   English

是否应该在提升活动的课堂内或在外面宣布代表?

[英]Should a delegate be declared inside the class that will raise the event, or outside?

I have seen various examples of event handling. 我已经看到了各种事件处理的例子。 Here is one: Event Sample . 这是一个: 事件样本

Sometimes I see the delegate declared outside the class that will raise the event (as in the link above), and sometimes inside (where I think it should be declared). 有时我看到在类之外声明的委托将引发事件(如上面的链接),有时在内部( 认为应该声明它)。

It makes more sense to me to declare the event inside the class that will raise the event. 它更有意义,我宣布,将引发该事件的类的事件。 The reason being that the event that the class will declare is really just some sugar coating for helper methods etc. that are really doing the adding to, subtracting from, and invoking of the delegate etc. 原因是该类将声明的事件实际上只是辅助方法等的一些糖涂层,它们实际上正在添加,减去和调用委托等。

Are there any best practices? 有没有最佳做法? Are there times when you would want to declare the delegate outside, and other times where you would want to declare the delegate inside? 是否有时候你想要在外面声明委托,有时你想在里面声明委托? If so, how should it be decided which to do? 如果是这样,应该如何决定做什么?

Typically, these days you'd create your own class derived from EventArgs , and then just use EventHandler<TEventArgs> - there's no need to create a separate delegate type. 通常,这些天你创建自己的类派生自EventArgs ,然后只使用EventHandler<TEventArgs> - 不需要创建单独的委托类型。 So instead of AlarmEventHandler , you'd use EventHandler<AlarmEventArgs> . 因此,不使用AlarmEventHandler ,而是使用EventHandler<AlarmEventArgs> The EventArgs -derived class should generally be top-level (ie non-nested). EventArgs派生的类通常应该是顶级的(即非嵌套的)。

I would declare them outside as they are ment to be used by other classes as well - the consumers of the event. 我会在外面宣布它们,因为它们也被其他类使用 - 事件的消费者。 I would keep the delegate in the same file as the class if the delegate is specific to this class. 如果委托特定于此类,我会将委托保留在与该类相同的文件中。

It's less of the problem if you use generic version of EventHandler<TEventAgrs> , available in .NET 2.0 and newer, as you need to declare your custom EventArgs only. 如果您使用.NET 2.0及更高版本中提供的EventHandler<TEventAgrs>通用版本,则不会出现问题,因为您只需要声明自定义EventArgs

If I remember correctly, there are few examples of public accessible nested "objects" in the CLR (classes/structs/delegates/enums). 如果我没记错的话,CLR中很少有公共可访问的嵌套“对象”(classes / structs / delegates / enums)。 So delegates normally are "external" to the class. 因此,代表通常是班级的“外部”。

BUT from the .NET 3.5 onward there has been the idea of using "generic" delegates ( Func<T> , Action<T> , Predicate<T> ) instead of an ever-increasing number of incompatible delegates 但是从.NET 3.5开始,一直有使用“泛型”委托( Func<T>Action<T>Predicate<T> )而不是越来越多的不兼容委托的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM