c#队列值意外更改 [英] c# Queue values changing inadvertently

查看:142
本文介绍了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?

这是完整的代码:

public class MA
{
    public static Queue<DateClose> MAMethod(Queue<DateClose> queue,
        Queue<DateClose> firstMASample, int period)
    {

        Queue<DateClose> sample = new Queue<DateClose>(firstMASample.ToArray());
        Queue<DateClose> movingAverageQueue = new Queue<DateClose>(queue.Count() + 1);
        // get the last item or initial MA value from the queue
        DateClose previousMa = firstMASample.LastOrDefault();
        sample = new Queue<DateClose>(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;
    }
}

DateClose类为:

The DateClose class is:

public class DateClose
{
    public DateTime Date { get; set; }
    public decimal Close { get; set; }
}

推荐答案

在C#中,对象引用是按值传递的,因此您正在排队对该对象的引用.队列中的引用仍指向相同的内存位置,因此,当您更改对象时,出队时将看到这些更改.

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.

乔恩·斯凯特(Jon Skeet)关于C#参数传递的文章

这篇关于c#队列值意外更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆