如何在C ++ / CLI中订阅C#事件

问题描述 投票:0回答:1

我在用C#订阅事件时没有问题。但是,我无法从c ++ / cli中找出执行相同操作的语法。

这是我在c#中的处理方式:

出版类:

public class Publisher
{
   private Publisher()
   {
      // prevent construction other than through instance method.
   }

   public static Publisher Instance()
   {
      if (mInstance == null) {
         mInstance = new Publisher();
      }

      return mInstance;
   }

   public void PublishItem(Item item)
   {
      var handler = OnNewItem;
      if (handler != null) {
         handler(this, new ItemEventArgs(reading));
      }
   }

public EventHandler<ItemEventArgs> OnNewItem;

订阅类

   public Subscribe()
   {
      Publisher.Instance().OnNewItem += OnNewItemReceived;
   }

    private void OnNewItemReceived(object src, ItemEventArgs itemArgs)
    {
       // do stuff
    }

如果我尝试相同的语法是c ++ / cli,则会收到操作数错误。

例如:

void MyCPPCLIClass::Subscribe()
{
    Publisher::Instance()->OnNewItem += MyCPPCLIClass::OnNewItemReceived);
}

void MyCPPCLIClass::OnNewItemReceived(System::Object^ src, Lib::ItemEventArgs^ itemArgs )
{
   //do stuff
}

有人可以帮我理解如何在c ++ / cli中实现Subscribing类吗?

c# event-handling c++-cli
1个回答
0
投票

类似这样的东西:

eventSource.MyCustomEvent +=
    gcnew EventSource::MyCustomEventHandlerDelegate(this, &MyCustomClass::MyCustomEventHandlerMethod);
© www.soinside.com 2019 - 2024. All rights reserved.