The code below changes the value of the first object placed on the queue. This is the code to put the first object on the queue:
//put the initial Ma value on the movingAverageQueue
movingAverageQueue.Enqueue(previousMa)
This line of code changes the first object above I already placed on the queue
previousMa.Close = previousMa.Close - sub/period;
What am I missing in my logic for this code?
here is the full code:
public class MA
{
public static Queue MAMethod(Queue queue,
Queue firstMASample, int period)
{
Queue sample = new Queue(firstMASample.ToArray());
Queue movingAverageQueue = new Queue(queue.Count() + 1);
// get the last item or initial MA value from the queue
DateClose previousMa = firstMASample.LastOrDefault();
sample = new Queue(firstMASample.Take(firstMASample.Count - 1));
DateClose mA = null;
decimal sub = 0;
DateClose add = null;
//put the initial Ma value on the movingAverageQueue
movingAverageQueue.Enqueue(previousMa);
foreach (DateClose d in queue.ToList())
{
mA = sample.Dequeue();
sub = mA.Close;
previousMa.Close = previousMa.Close - sub/period;
add = d;
sample.Enqueue(d);
previousMa.Close = previousMa.Close + add.Close/period;
previousMa.Date = add.Date;
movingAverageQueue.Enqueue(previousMa);
queue.Dequeue();
}
return movingAverageQueue;
}
}
The DateClose class is:
public class DateClose
{
public DateTime Date { get; set; }
public decimal Close { get; set; }
}
解决方案
In C#, object references are passed by value, and so you are enqueing a reference to that object. The reference in the queue is still pointing to the same memory location, and so when you alter the object you will see those changes when you dequeue that object reference.