Super-simple example of C# observer/observable with delegates(带有委托的 C# 观察者/可观察的超级简单示例)
问题描述
我最近开始深入研究 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# 观察者/可观察的超级简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有委托的 C# 观察者/可观察的超级简单示例
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01