繁体   English   中英

反应性扩展:包装自定义委托事件

[英]Reactive extensions: Wrap custom delegate event

如何使用Observable.FromEvent在Rx中包装这些自定义委托?

public delegate void EmptyDelegate();
public delegate void CustomDelegate( Stream stream, Dictionary<int, object> values );

EmptyDelegate

这是一个无参数的委托,但是流需要一个类型 - 为此目的,Rx定义了Unit ,以指示我们只对出现感兴趣的事件类型 - 也就是说,没有有意义的有效负载。

假设您有此委托的实例声明为:

public EmptyDelegate emptyDelegate;

然后你可以这样做:

var xs = Observable.FromEvent<EmptyDelegate, Unit>(
    h => () => h(Unit.Default),
    h => emptyDelegate += h,
    h => emptyDelegate -= h);

xs.Subscribe(_ => Console.WriteLine("Invoked"));

emptyDelegate(); // Invoke it

CustomDelegate

假设您需要流和值,您将需要一个类型来携带这些,如:

public class CustomEvent
{
    public Stream Stream { get; set; }
    public Dictionary<int,object> Values { get; set; }
}

然后假设委托的实例被声明:

public CustomDelegate customDelegate;

你可以做:

var xs = Observable.FromEvent<CustomDelegate, CustomEvent>(
    h => (s, v) => h(new CustomEvent { Stream = s, Values = v }),
    h => customDelegate += h,
    h => customDelegate -= h);

xs.Subscribe(_ => Console.WriteLine("Invoked"));

// some data to invoke the delegate with
Stream stream = null;
Dictionary<int,object> values = null;

// and invoke it
customDelegate(stream,values);

有关Observable.FromEvent的详细说明,请参阅如何使用Observable.FromEvent而不是FromEventPattern并避免使用字符串文字事件名称

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM