将自定义EventHandler转换为IObservable

时间:2018-09-26 00:47:16

标签: c# reactive-programming

我目前正在尝试通过尝试将旧项目转换为Reactive来学习C#中的Reactive编程,我使用dll文件连接到生物识别机器,这是dll暴露的一些事件,我如何转换此事件可以使用Observable.FromEvent进行观察?

// I use the event like this,
axCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM_OnAttTransactionEx);

这是生成的元数据

#region Assembly Interop.zkemkeeper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// C:\Project\C#\obj\Debug\Interop.zkemkeeper.dll
#endregion

using System.Runtime.InteropServices;

namespace zkemkeeper
{
    [ComVisible(false)]
    [TypeLibType(16)]
    public delegate void _IZKEMEvents_OnAttTransactionExEventHandler(
        string EnrollNumber, 
        int IsInValid,
        int AttState,
        int VerifyMethod,
        int Year,
        int Month,
        int Day,
        int Hour,
        int Minute,
        int Second,
        int WorkCode);
}

1 个答案:

答案 0 :(得分:1)

即使我是Reactive编程的新手,但由于没有其他答案,我会尝试, 您将在这里需要两件事。 第一,为事件args使用包装器。

internal class MyArgs
{
    public string EnrollNumber;
    public int IsInValid;
    public int AttState;
    public int VerifyMethod;
    public int Year;
    public int Month;
    public int Day;
    public int Hour;
    public int Minute;
    public int Second;
    public int WorkCode;
}

然后使用FromEvent和转换器将您的args转换为MyArgs。

  var observable = Observable.FromEvent<_IZKEMEvents_OnAttTransactionExEventHandler, MyArgs>(
         converter => new _IZKEMEvents_OnAttTransactionExEventHandler(
                         (enrollNumber, isInValid, attState, verifyMethod, year, month, day, hour, minute, second, workCode)
                         => converter(new MyArgs
                         {
                             EnrollNumber = enrollNumber,
                             IsInValid = isInValid,
                             AttState = attState,
                             VerifyMethod = verifyMethod,
                             Day=day,
                             Hour=hour,
                             Minute=minute,
                             Month=month,
                             Second=second,
                             WorkCode=workCode,
                             Year=year
                         })
                 ),
         handler => axCZKEM.OnAttTransactionEx += handler,
         handler => axCZKEM.OnAttTransactionEx -= handler);