与事件集成,其中委托具有多个参数且没有EventArgs

时间:2016-08-03 09:17:18

标签: c# system.reactive

FromEventFromEventPattern方法似乎没有超载,只有在有多个IObservable<T>TDelegate类型的EventArgs事件时才会转换为类型为public event Action<int, int> SomethingHappened; public event Func<string, int> SomethingElseHappened; 的事件参数并没有EventArgs

例如似乎我们无法将以下内容转换为可观察对象。

TDelegate

我们要么必须在某处 EventArgs,要么public event NameChangedHandler NameChanged; public event EventHandler RollNumberChanged; public event EventHandler<AgeChangedEventArgs> AgeChanged; public delegate void NameChangedHandler( object sender, NameChangedEventArgs e); 只有一个参数在其签名中。因此,以下内容是可转换的,因为它们的隐式委托中有T

public event Action<Tuple<string, string>> ClassChanged;

这个也可以转换,因为它的参数中只有一个public event Action<T1, T2...> ItHappened;

_self

如果我有这样的事件该怎么办:

_blank

2 个答案:

答案 0 :(得分:2)

使用class Tester

public class Tester
{
    public void FireEvent(int i1, int i2, int i3)
    {
        if(ItHappened != null)
            ItHappened(i1, i2, i3);
    }

    public event Action<int, int, int> ItHappened;
}

您可以将此签名Observable.FromEvent<TDelegate, TEventArgs> (Func<Action<TEventArgs>, TDelegate>, Action<TDelegate>, Action<TDelegate>)与转换函数一起使用,如下所示:

var t3 = new Tester();
IObservable<Tuple<int, int, int>> observable = Observable.FromEvent<Action<int, int, int>, Tuple<int, int, int>>(
    onNextHandler => (int i1, int i2, int i3) => onNextHandler(Tuple.Create(i1, i2, i3)),
    h => t3.ItHappened += h,
    h => t3.ItHappened -= h);

using (var disposable = observable.Subscribe(t => Console.WriteLine($"{{{t.Item1}, {t.Item2}, {t.Item3}}}")))
{
    t3.FireEvent(1, 2, 3);
}
t3.FireEvent(1, 2, 3);

对重载here有一个很好的参考。

答案 1 :(得分:2)

我必须说我在事件public event Func<string, int> SomethingElseHappened;上挣扎,但这是一个奇怪的事件,事件实际上会返回一个值。

然而,使用public event Action<int, int> SomethingHappened;,使用FromEvent非常容易。

鉴于此课程:

public class Foo
{
    public event Action<int, int> SomethingHappened;

    public void OnSomethingHappened(int x, int y)
    {
        this.SomethingHappened?.Invoke(x, y);
    }
}

...然后这段代码:

var foo = new Foo();

var fooSomethingHappened =
    Observable
        .FromEvent<Action<int, int>, Tuple<int, int>>(
            a => (x, y) => a(Tuple.Create(x, y)),
            h => foo.SomethingHappened += h,
            h => foo.SomethingHappened -= h);

fooSomethingHappened
    .Subscribe(t =>
        Console.WriteLine("SomethingHappened: {0} & {1}", t.Item1, t.Item2));

foo.OnSomethingHappened(3, 5);

...给我们:

SomethingHappened: 3 & 5