C ++ / Cli将回调添加到托管Action <t1,t2>对象</t1,t2>

时间:2012-10-30 20:06:19

标签: c# delegates c++-cli

在c#类中,我有以下内容:

public class Myclass
{
  public Action<string, string> MyDelegate { get; set;}

  public void CallingAction()
  {
    MyDelegate("string1", "string2");
  }
}

在C ++ / Cli中,我想向委托添加一个新函数。

public ref class MyCliClass
{
  public :
  MyCliClass()
  {
    MyClass^ myClassInstance = gcnew MyClass();
    MyCliDelegate^ myDelegateInstance = gcnew MyCliDelegate(this, &MyCliClass::FunctionToCall);
    myClassInstance->MyDelegate += myDelegateInstance;
  }

  void FunctionToCall(string^ string1, string^ string2)
  {
    // Some stuff to do
  }

  private :
  void delegate MyCliDelegate(string^,string^);
}

这给了我错误:

error C3365: operator '+' : differing operands of type 'System::Action<T1, T2> ^' and 'MyCliClass::FunctionToCall^'

如何简单地将“FunctionToCall”添加到C#Delegate中,这样当调用“CallingAction”时,还会调用“FunctionToCall”?

谢谢

修改/ ANSWER 这是新的Cli / Class

public ref class MyCliClass
{
  public :
  MyCliClass()
  {
    MyClass^ myClassInstance = gcnew MyClass();
    myClassInstance->MyDelegate += gcnew Action<string^,string^>^(this, &MyCliClass::FunctionToCall);
  }

  void FunctionToCall(string^ string1, string^ string2)
  {
    // Some stuff to do
  }
}

1 个答案:

答案 0 :(得分:1)

等效代表类型不可转换 您需要将委托实例声明为Action<string^, string^>^