带有委托的 C# 观察者/可观察的超级简单示例

Super-simple example of C# observer/observable with delegates(带有委托的 C# 观察者/可观察的超级简单示例)
本文介绍了带有委托的 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# 观察者/可观察的超级简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)