如何在C#中将回调方法传递给另一个类

时间:2018-07-30 19:32:53

标签: c# dll callback delegates

我正在使用C#,并且已经创建了一个App A和一个DLLB。 我希望能够执行以下操作:

  1. 在App A中,创建我的回调方法:

    public void MyAppMethod(string inComing){
        Debug.WriteLine("callback returned: " + inComing);
    }
    
  2. 在App A中,在B中设置Call​​Back方法,例如B.SetCallback(MyAppMethod);

  3. 在DLL B中,使用回调函数返回一个字符串:

    private void SomeMethod(){
        //do some stuff
        MyAppMethod("hello");
    }
    

我该如何设置?

2 个答案:

答案 0 :(得分:0)

使用事件:

应用A:

public void MyAppMethod(string inComing){
    Debug.WriteLine("callback returned: " + inComing);
}

B.MyAppMethod += MyAppMethod;

应用B:

public event Action<string> MyAppMethod;
private void SomeMethod(){
    //do some stuff
    if(MyAppMethod!=null) MyAppMethod("hello");
}

使用代表:

应用A:

public void MyAppMethod(string inComing){
    Debug.WriteLine("callback returned: " + inComing);
}

B.MyAppMethod = MyAppMethod;

应用B:

public Action<string> MyAppMethod;
private void SomeMethod(){
    //do some stuff
    if(MyAppMethod!=null) MyAppMethod("hello");
}

这些代码将按原样工作。但是,在使用此代码之前,必须考虑许多重要事项,您会发现on the web

答案 1 :(得分:0)

这是我最终使用的代码。

APP A:

public void MyCallBack(string status)
{
   // Add callback text to the status window
   StatTxt.AppendText(status);
}

// Set the callback method in DLL B
B.HollaBack = MyCallBack;

DLL B:

public delegate void CallBackDelegate(string status);  
public CallBackDelegate HollaBack
{
   get; set;
}

private void DoCallBack(string inMsg)
{
   // Make sure the callback method was set
   if (HollaBack != null)
   {
      // send text to the callback method
      HollaBack(inMsg);
   }
}

// Invoke the callback anywhere within DLL B
DoCallBack("show this in the status window");