我试图填充移动平均队列,但是我获得了相同的日期并关闭了移动平均队列中的所有对象。我被困在如何不获取指向同一对象的引用而不是获取对象中的当前值并将该值放在队列中的问题上。
public class MA
{
public static Queue<DateClose> MAMethod(Queue<DateClose> queue,
Deque<DateClose> firstMASample, int period)
{
Deque<DateClose> sample = new Deque<DateClose>(firstMASample.ToArray());
Queue<DateClose> movingAverageQueue = new Queue<DateClose>(queue.Count() + 1);
// get the last item or initial MA value from the queue
DateClose mA = sample.RemoveFromBack();
DateClose dateClose = null;
decimal sub = 0;
DateClose add = null;
//put the initial Ma value on the movingAverageQueue
movingAverageQueue.Enqueue(mA);
foreach (DateClose d in queue.ToList())
{
dateClose = sample.RemoveFromFront();
sub = dateClose.Close;
// subtract previous closing from new current MA
mA.Close = mA.Close - sub/period;
// add the new closing to new current MA
add = d;
sample.AddToBack(d);
mA.Close = mA.Close + add.Close/period;
mA.Date = add.Date;
movingAverageQueue.Enqueue(mA);
queue.Dequeue();
}
return movingAverageQueue;
}
}
movingAverageQueue具有相同的Date和Close值。
答案 0 :(得分:0)
我通过在for循环中创建两个新对象解决了按值访问而不是按引用访问的问题,
public static Deque<DateClose> MAMethod(Queue<DateClose> queue,
Deque<DateClose> firstMASample, int period)
{
Deque<DateClose> sample = new Deque<DateClose>(firstMASample.ToArray());
Deque<DateClose> movingAverageQueue = new Deque<DateClose>(queue.Count() + 1);
// get the last item or initial MA value from the queue
DateClose mA = sample.RemoveFromBack();
//DateClose dateClose = null;
decimal sub = 0;
DateClose add = null;
//put the initial Ma value on the movingAverageQueue
movingAverageQueue.AddToBack(mA);
foreach (DateClose d in queue.ToList())
{
// create a new object for add subtraction moving averages
DateClose dateClose = new DateClose(sample.RemoveFromFront());
sub = dateClose.Close;
// create a new object to place the new moving average on the queue
DateClose mAQueueValue = new DateClose(movingAverageQueue.Last());
// subtract previous closing from new current MA
mAQueueValue.Close = mAQueueValue.Close - sub/period;
// add the new closing to new current MA
add = d;
sample.AddToBack(d);
mAQueueValue.Close = mAQueueValue.Close + add.Close/period;
mAQueueValue.Date = add.Date;
movingAverageQueue.AddToBack(mAQueueValue);
queue.Dequeue();
}
return movingAverageQueue;
}