gpt4 book ai didi

c# - C# 中的 IObserver 和 IObservable 用于观察者与委托(delegate)、事件

转载 作者:可可西里 更新时间:2023-11-01 03:12:24 26 4
gpt4 key购买 nike

我要做的就是实现观察者模式。

所以,我想到了这个解决方案:

我们有一个 PoliceHeadQuarters,其主要工作是向所有订阅它的人发送通知。假设 DSP、Inspector 和 SubInspector 类订阅了 PoliceHeadQuarters。

使用我写的事件和委托(delegate)

public class HeadQuarters 
{
public delegate void NewDelegate(object sender, EventArgs e);
public event EventHandler NewEvent;
public void RaiseANotification()
{
var handler = this.NewEvent;
if (handler != null)
{
handler(this, new EventArgs());
}
}
}

public class SubInspector
{
public void Listen(object sender, EventArgs e)
{
MessageBox.Show(string.Format("Event Notification received by sender = {0} with eventArguments = {1}", sender, e.ToString()));
}
}

public class Inspector
{
public void Listen(object sender, EventArgs e)
{
MessageBox.Show(string.Format("Event Notification received by sender = {0} with eventArguments = {1}", sender, e.ToString()));
}
}

这就是我调用它的方式

       var headQuarters = new HeadQuarters();
var SubInspector = new SubInspector();
var Inspector = new Inspector();
headQuarters.NewEvent += Inspector.Listen;
headQuarters.NewEvent += SubInspector.Listen;
headQuarters.RaiseANotification();

因此,每当调用 RaiseANotification() 函数时,Inspector 和 SubInspector 类都会收到通知。

DotNet Framework 4, 4.5 似乎支持一种新的方式,叫做IObserver 和IObservable。

谁能给我一个在上述场景中使用 IObservable 和 IObserver 模式的 super 简单示例?我用谷歌搜索只是为了发现互联网上的可用示例过于臃肿且难以理解。

我的想法:(可能我认为这是错误的)

  class DSP : IObserver //since it observes the headquarters ?
class PoliceHeadQuarters: IObservable // since here's where we send the notifications ?

提前致谢。

编辑:有人还说 MSDN 文档对于 IObservable @ 也是不正确的 IObservable vs Plain Events or Why Should I use IObservable? .

最佳答案

这里是对 MSDN 示例的修改以适合您的框架:

    public struct Message
{
string text;

public Message(string newText)
{
this.text = newText;
}

public string Text
{
get
{
return this.text;
}
}
}

public class Headquarters : IObservable<Message>
{
public Headquarters()
{
observers = new List<IObserver<Message>>();
}

private List<IObserver<Message>> observers;

public IDisposable Subscribe(IObserver<Message> observer)
{
if (!observers.Contains(observer))
observers.Add(observer);
return new Unsubscriber(observers, observer);
}

private class Unsubscriber : IDisposable
{
private List<IObserver<Message>> _observers;
private IObserver<Message> _observer;

public Unsubscriber(List<IObserver<Message>> observers, IObserver<Message> observer)
{
this._observers = observers;
this._observer = observer;
}

public void Dispose()
{
if (_observer != null && _observers.Contains(_observer))
_observers.Remove(_observer);
}
}

public void SendMessage(Nullable<Message> loc)
{
foreach (var observer in observers)
{
if (!loc.HasValue)
observer.OnError(new MessageUnknownException());
else
observer.OnNext(loc.Value);
}
}

public void EndTransmission()
{
foreach (var observer in observers.ToArray())
if (observers.Contains(observer))
observer.OnCompleted();

observers.Clear();
}
}

public class MessageUnknownException : Exception
{
internal MessageUnknownException()
{
}
}

public class Inspector : IObserver<Message>
{
private IDisposable unsubscriber;
private string instName;

public Inspector(string name)
{
this.instName = name;
}

public string Name
{
get
{
return this.instName;
}
}

public virtual void Subscribe(IObservable<Message> provider)
{
if (provider != null)
unsubscriber = provider.Subscribe(this);
}

public virtual void OnCompleted()
{
Console.WriteLine("The headquarters has completed transmitting data to {0}.", this.Name);
this.Unsubscribe();
}

public virtual void OnError(Exception e)
{
Console.WriteLine("{0}: Cannot get message from headquarters.", this.Name);
}

public virtual void OnNext(Message value)
{
Console.WriteLine("{1}: Message I got from headquarters: {0}", value.Text, this.Name);
}

public virtual void Unsubscribe()
{
unsubscriber.Dispose();
}
}

public class Program
{
public static void Main(string[] args)
{
Inspector inspector1 = new Inspector("Greg Lestrade");
Inspector inspector2 = new Inspector("Sherlock Holmes");

Headquarters headquarters = new Headquarters();

inspector1.Subscribe(headquarters);
inspector2.Subscribe(headquarters);

headquarters.SendMessage(new Message("Catch Moriarty!"));
headquarters.EndTransmission();

Console.ReadKey();
}
}

关于c# - C# 中的 IObserver 和 IObservable 用于观察者与委托(delegate)、事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17020011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com