簡體   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