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

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


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


public void MyAppMethod(string inComing){

    Debug.WriteLine("callback returned: " + inComing);

}

在 App A 中,在 B 中设置 CallBack 方法,例如 B.SetCallback(MyAppMethod);


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


private void SomeMethod(){

    //do some stuff

    MyAppMethod("hello");

}

我该如何设置?


慕斯王
浏览 240回答 2
2回答

RISEBY

使用事件:应用程序A:public void MyAppMethod(string inComing){&nbsp; &nbsp; Debug.WriteLine("callback returned: " + inComing);}B.MyAppMethod += MyAppMethod;应用程序B:public event Action<string> MyAppMethod;private void SomeMethod(){&nbsp; &nbsp; //do some stuff&nbsp; &nbsp; if(MyAppMethod!=null) MyAppMethod("hello");}使用委托:应用程序A:public void MyAppMethod(string inComing){&nbsp; &nbsp; Debug.WriteLine("callback returned: " + inComing);}B.MyAppMethod = MyAppMethod;应用程序B:public Action<string> MyAppMethod;private void SomeMethod(){&nbsp; &nbsp; //do some stuff&nbsp; &nbsp; if(MyAppMethod!=null) MyAppMethod("hello");}这些代码将按原样工作。但是,在使用此代码之前,您必须考虑许多重要事项,您可以在网上找到这些内容

慕标5832272

这是我最终使用的代码。应用程序一:public void MyCallBack(string status){&nbsp; &nbsp;// Add callback text to the status window&nbsp; &nbsp;StatTxt.AppendText(status);}// Set the callback method in DLL BB.HollaBack = MyCallBack;动态链接库 B:public delegate void CallBackDelegate(string status);&nbsp;&nbsp;public CallBackDelegate HollaBack{&nbsp; &nbsp;get; set;}private void DoCallBack(string inMsg){&nbsp; &nbsp;// Make sure the callback method was set&nbsp; &nbsp;if (HollaBack != null)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; // send text to the callback method&nbsp; &nbsp; &nbsp; HollaBack(inMsg);&nbsp; &nbsp;}}// Invoke the callback anywhere within DLL BDoCallBack("show this in the status window");
打开App,查看更多内容
随时随地看视频慕课网APP