在 C# 中,类和接口(interface)可以有事件
:
public class Foo
{
public event Action SomethingHappened;
public void DoSomething()
{
// yes, i'm aware of the potential NRE
this.SomethingHappened();
}
}
这有助于使用最少的样板代码实现基于推送的通知,并启用多订阅者模型,以便许多观察者可以收听事件:
var foo = new Foo();
foo.SomethingHappened += () => Console.WriteLine("Yay!");
foo.DoSomething(); // "Yay!" appears on console.
Scala 中是否有等效的习语?我正在寻找的是:
- 最少的样板代码
- 单个发布者,多个订阅者
- 附加/分离订阅者
它在 Scala 文档中的使用示例会很棒。我不是在 Scala 中寻找 C# 事件的实现。相反,我在 Scala 中寻找等效的习语。
最佳答案
scala 的惯用方式是不使用观察者模式。 参见 Deprecating the Observer Pattern .
看看this answer实现。
关于c# - Scala 中 C# 事件的惯用等价物是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14503306/