我正在使用C#,并且已经创建了一个App A和一个DLLB。 我希望能够执行以下操作:
在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");
}
我该如何设置?
答案 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");