在 C# 中,我认为您正在寻找的东西称为事件。它们是一种语言功能,允许类实例以其他类实例可以订阅的方式公开公共委托。只允许暴露类引发事件。
在您的示例中:
public class ClassB {
// Note the syntax at the end here- the "(s, e) => { }"
// assigns a no-op listener so that you don't have to
// check the event for null before raising it.
public event EventHandler<MyEventArgs> MyEvent = (s, e) => { }
public void DoMyWork() {
// Do whatever
// Then notify listeners that the event was fired
MyEvent(this, new MyEventArgs(myWorkResult));
}
}
public class ClassA {
public ClassA(ClassB worker) {
// Attach to worker's event
worker.MyEvent += MyEventHandler;
// If you want to detach later, use
// worker.MyEvent -= MyEventHandler;
}
void MyEventHandler(Object sender, MyEventArgs e) {
// This will get fired when B's event is raised
}
}
public class MyEventArgs : EventArgs {
public String MyWorkResult { get; private set; }
public MyEventArgs(String myWorkResult) { MyWorkResult = myWorkResult; }
}
请注意,以上将是同步的。我的理解是Objective-C委托都是Actor模式,所以它们是异步的。要使上述异步,您需要深入研究线程(可能想要谷歌“C#线程池”)。