c#队列取值,c#队列值意外更改

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值