将其添加为新答案,因为它完全不同...
因此,如果您致力于执行操作员重载路线,那么您需要这样做(嗯,至少是一种方式)......老实说,我不喜欢这种方法 -虽然它确实使查询编写更加简洁,但 DSL 方法具有类似的“简洁性”,但在不依赖运算符重载的意义上更清晰。
public static class ArithmeticStreamExt
{
public static ArithmeticStream Wrap(this IObservable<double> src)
{
return new ArithmeticStream(src);
}
public static ArithmeticStream Const(this double constValue)
{
return new ArithmeticStream(Observable.Return(constValue));
}
}
public class ArithmeticStream
{
private IObservable<double> _inner;
public ArithmeticStream(IObservable<double> source)
{
_inner = source;
}
public IObservable<double> Source {get { return _inner; }}
public static ArithmeticStream operator +(
ArithmeticStream left,
ArithmeticStream right)
{
return new ArithmeticStream(
left._inner.CombineLatest(right._inner, (l, r) => l + r));
}
public static ArithmeticStream operator -(
ArithmeticStream left,
ArithmeticStream right)
{
return new ArithmeticStream(
left._inner.CombineLatest(right._inner, (l, r) => l - r));
}
public static ArithmeticStream operator *(
ArithmeticStream left,
ArithmeticStream right)
{
return new ArithmeticStream(
left._inner.CombineLatest(right._inner, (l, r) => l * r));
}
public static ArithmeticStream operator /(
ArithmeticStream left,
ArithmeticStream right)
{
return new ArithmeticStream(
left._inner.CombineLatest(right._inner, (l, r) => l / r));
}
public static ArithmeticStream operator +(
ArithmeticStream left,
IObservable<double> right)
{
return new ArithmeticStream(
left._inner.CombineLatest(right, (l, r) => l + r));
}
public static ArithmeticStream operator -(
ArithmeticStream left,
IObservable<double> right)
{
return new ArithmeticStream(
left._inner.CombineLatest(right, (l, r) => l - r));
}
public static ArithmeticStream operator *(
ArithmeticStream left,
IObservable<double> right)
{
return new ArithmeticStream(
left._inner.CombineLatest(right, (l, r) => l * r));
}
public static ArithmeticStream operator /(
ArithmeticStream left,
IObservable<double> right)
{
return new ArithmeticStream(
left._inner.CombineLatest(right, (l, r) => l / r));
}
}
还有一个测试台:
void Main()
{
var s1 = new Subject<double>();
var s2 = new Subject<double>();
var s3 = new Subject<double>();
var s4 = new Subject<double>();
var result = (s1.Wrap() + s2) / s3 + (s4.Wrap() * 2.0.Const());
using(result.Source.Subscribe(Console.WriteLine))
{
s1.OnNext(1.0);
s2.OnNext(2.0);
s3.OnNext(3.0);
s4.OnNext(4.0);
}
}