我最近开始深入研究 C#,但我一生无法弄清楚在语言中实现观察者/可观察模式时委托是如何工作的.
I recently started digging into C# but I can't by my life figure out how delegates work when implementing the observer/observable pattern in the language.
谁能给我一个超级简单的例子来说明它是如何完成的?我用谷歌搜索了这个,但我发现的所有示例要么过于具体,要么过于臃肿".
Could someone give me a super-simple example of how it is done? I have googled this, but all of the examples I found were either too problem-specific or too "bloated".
观察者模式通常使用 事件.
The observer pattern is usually implemented with events.
这是一个例子:
using System;
class Observable
{
public event EventHandler SomethingHappened;
public void DoSomething() =>
SomethingHappened?.Invoke(this, EventArgs.Empty);
}
class Observer
{
public void HandleEvent(object sender, EventArgs args)
{
Console.WriteLine("Something happened to " + sender);
}
}
class Test
{
static void Main()
{
Observable observable = new Observable();
Observer observer = new Observer();
observable.SomethingHappened += observer.HandleEvent;
observable.DoSomething();
}
}
有关更多详细信息,请参阅链接文章.
See the linked article for a lot more detail.
请注意,上面的示例使用 C# 6 null-conditional 运算符来安全地实现 DoSomething
以处理未订阅 SomethingHappened
的情况,因此为空.如果您使用的是旧版本的 C#,则需要这样的代码:
Note that the above example uses C# 6 null-conditional operator to implement DoSomething
safely to handle cases where SomethingHappened
has not been subscribed to, and is therefore null. If you're using an older version of C#, you'd need code like this:
public void DoSomething()
{
var handler = SomethingHappened;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
这篇关于带有委托的 C# 观察者/可观察的超级简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!