问题描述
我正在使用转换工具将C#项目移植到C ++/CLI项目.
在C#项目中,有一个代码部分,其中在如果"条件下将事件"与空"进行比较.
Hi,
I am porting a C# project to C++/CLI project by using a conversion tool.
In C# project has a code section in which ‘Event’ is compared with ‘null’ in an ‘if’ condition.
public event RawFileReadHandler EventRead;
if ( this.EventRead != null )
{
this.EventRead( this, new RawFileReadArgs( total, current++, file, abort ) );
}
在C ++/CLI中将相同的代码段转换为:
Same code section was converted in C++/CLI as:
public:
event RawFileReadHandler ^EventRead;
if (this->EventRead != nullptr)
{
this->EventRead(this, gcnew RawFileReadArgs(total, current++, file, abort));
}
但是,转换后的代码中的此"if"语句会产生编译时错误,因为使用要求成员"成为数据成员".
我想这是不允许在如果"条件下将事件"与"nullptr"进行比较的.
But, this ‘if’ statement in the converted code gives a compile time error as, "Usage requires ''member'' to be a data member".
I guess it is not allowing ‘Event’ to be compared in ‘if’ condition with ‘nullptr’.
Is there any other way by which this ‘Event’ comparison with ‘nullptr’ can be written in C++/CLI?
推荐答案
private:
// This is your private event.
System::EventHandler^ privateHandler;
public:
// This is the public event.
event System::EventHandler^ PublicHandler
{
void add(System::EventHandler^ handler )
{
//just attach user handler to your private event
privateHandler += handler;
}
void remove( System::EventHandler^ handler )
{
//just detach the user handler from your private handler
privateHandler -= handler;
}
void raise(Object^ sender, EventArgs^ e)
{
//raise your private event
privateHandler(s, e);
}
}
检查调用列表:
Checking the invocation list:
if (privateHandler->GetInvocationList()->Length == 0)
{
//there is no handler attached to this event
}
else
{
// at least one handler is attached to this event
// call the handlers or do whatever you want...
privateEvent(...);
}
我希望这能回答您的问题.
I hope this answers your question.
这篇关于可以在C ++/CLI中将“事件"与"nullptr"进行比较吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!