问题描述
您可以像这样在C#中使用委托(直接来自VS帮助的代码)-
You use delegates in C# like so (code straight from VS help) -
public delegate void FireEventHandler(object sender, FireEventArgs fe);
public event FireEventHandler FireEvent;
并提出活动-
and to raise the event -
if (FireEvent != null)
FireEvent(this,args);
如果事件没有委托,则必须检查它是否为非null以避免NullReferenceExceptions. (这里有关于在测试null之前复制FireEvent的好处,但我们暂时将其忽略)
等效于C ++的样子(再次来自VS帮助)
You have to check it''s not null to avoid NullReferenceExceptions if the event has no delegates. (There are niceties here about copying FireEvent before testing for nullness but we''ll ignore that for now)
The C++ equivalent looks like this (again from VS help)
delegate void FireEventHandler(Object^ sender, FireEventArgs^ fe );
event FireEventHandler^ FireEvent;
并调用-
and to invoke -
FireEvent( this, fireArgs );
这里没有检查是否为空.您不需要(您不会在空事件中获得NullReferenceExceptions),但是您可能希望这样做,例如以避免在分配事件arg之前分配事件args或您需要执行的其他任何操作.
但是你不能.您可能会想尝试-
There''s no checking for null here. You don''t need to (you don''t get NullReferenceExceptions on an empty event) but you might want to, e.g. to avoid allocating event args or anything else you need to do before raising the event.
But you can''t. You might be tempted to try -
if (FireEvent)...
会出现编译器错误
错误C3918:用法要求"FireEvent"成为数据成员
但是,如果您不使用event关键字,即
and you get a compiler error
error C3918: usage requires ''FireEvent'' to be a data member
However, if you don''t use the event keyword, i.e.
delegate void FireEventHandler(Object^ sender, FireEventArgs^ fe );
FireEventHandler^ FireEvent;
那么您可以检查是否为空,一切似乎都可以正常进行,包括从c#订阅该事件.
但是我看过的所有文档都说您必须使用event关键字,而不使用它会在继承和从C#代码访问事件方面带来问题.
所以我的问题是,这是怎么回事?理想情况下,如何在C ++中执行if (FireEvent != null)
的等效功能?
then you can check for nullness and everything appears to work, including subscribing to the event from c#.
But all documentation I''ve looked as says you have to use the event keyword, and not using it has problems with inheritance and accessing the events from C# code.
So my question is, what''s going on here? Ideally, how can I perform the equivalent of if (FireEvent != null)
in C++?
推荐答案
这篇关于在C ++.NET中检查空委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!