gpt4 book ai didi

c# - 如何消除累加器中的条件?

转载 作者:行者123 更新时间:2023-11-30 17:01:23 25 4
gpt4 key购买 nike

给定这段代码:

private static IObservable<Stock> ToStock(this IObservable<decimal> prices, string symbol)
{
return prices.Scan(
default(Stock),
(previous, price) => previous == default(Stock)
? new Stock(symbol, price)
: previous.Change(price));
}

// The signature for Stock.Change() looks like this. Stock is an immutable class.
// public Stock Change(decimal newCurrentPrice)

我想消除每次调用累加器时发生的检查 previous == default(Stock)。我所拥有的是第一项与其余项不同的行为。我不确定如何简单地使用 LINQ for Rx 来表达这一点。

编辑。这是 Stock 的代码,这可能有助于解释为什么我不能给它一个价格的标记值。

public class Stock
{
private readonly decimal _current;
private readonly decimal _dayHigh;
private readonly decimal _dayLow;
private readonly decimal _dayOpen;
private readonly decimal _lastChange;
private readonly string _symbol;

public Stock(string symbol, decimal price)
{
if (symbol == null) throw new ArgumentNullException("symbol");
if (price <= 0) throw new ArgumentOutOfRangeException("price", "Price must be greater than zero.");

_symbol = symbol;
_current = _dayOpen = _dayLow = _dayHigh = price;
}

private Stock(Stock original, decimal newCurrent)
{
if (original == null) throw new ArgumentNullException("original");

_symbol = original.Symbol;
_current = newCurrent;
_dayOpen = original.DayOpen;
_dayHigh = Math.Max(newCurrent, original.DayHigh);
_dayLow = Math.Min(newCurrent, original.DayLow);
_lastChange = newCurrent - original.Current;
}

public string Symbol { get { return _symbol; } }
public decimal Current { get { return _current; } }
public decimal LastChange { get { return _lastChange; } }
public decimal DayOpen { get { return _dayOpen; } }
public decimal DayLow { get { return _dayLow; } }
public decimal DayHigh { get { return _dayHigh; } }
public decimal DayChange { get { return Current - DayOpen; } }
public double DayChangeRatio { get { return (double) Math.Round(DayChange/Current, 4); } }

public Stock Change(decimal newCurrent)
{
return newCurrent == Current
? this
: new Stock(this, newCurrent);
}
}

最佳答案

我想到了这个解决方案:

private static IObservable<Stock> ToStock2(this IObservable<decimal> prices, string symbol)
{
Func<Stock, decimal, Stock> accumulator = (_, firstPrice) =>
{
accumulator = (previous, price) => previous.Change(price);
return new Stock(symbol, firstPrice);
};

return prices.Scan(default(Stock), (previous, price) => accumulator(previous, price));
}

它在第一次调用时使用自变异的 Func 变量来改变行为,但快速测试(以 50 万个价格运行)表明它的执行速度比原来慢 2-3%方法,而且代码不太清晰。与为每个项目调用第二个 Func 相比,.NET 似乎更有效地为每个项目执行相等比较器。我不确定是否有任何方法可以对其进行优化,使其比原来的表现更好,以证明清晰度降低是合理的。

关于c# - 如何消除累加器中的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21124130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com