每次创建对象时创建新队列

时间:2011-06-08 18:19:04

标签: c# class object queue

我创建了一个简单的类来过滤数据流中的数据。问题是如果我使用多个ValueFilter对象,它们都使用相同的队列。我希望每个ValueFilter对象都有一个单独的队列。我在我的主程序中声明ValueFilter是这样的:ValueFilter filter = new ValueFilter();我应该使用某种构造函数吗?

using System;
using Microsoft.SPOT;
using System.Collections;
namespace foo
{
    class ValueFilter
    {
        private const int FILTER_QUEUE_SIZE = 10;
        private static int sum = 0;
        private static Queue queue = new Queue();

        public int FilterValue(int value)
        {
            if (queue.Count >= FILTER_QUEUE_SIZE)
            {

                if (System.Math.Abs((int)(value - sum/queue.Count)) < 3000)
                {
                    queue.Enqueue(value);
                    sum += (int)(value - (int)queue.Dequeue());                  
                }
            }
            else
            {
                queue.Enqueue(value);
                sum += (int)value;
            }

            return sum / queue.Count;
        }
}

3 个答案:

答案 0 :(得分:3)

由于Queue似乎是私有的,所以您需要做的就是删除static修饰符:

//private static int sum = 0;
//private static Queue queue = new Queue();
private int sum = 0;
private Queue queue = new Queue();

现在每个ValueFilter实例都有自己的sumqueue个实例。非静态成员是实例成员。

答案 1 :(得分:1)

您将队列变量声明为static。如果每个FilterValue需要一个队列,请不要使用静态队列,请为其使用实例变量。

答案 2 :(得分:1)

您将“queue”声明为静态,因此它存在于ValueFilter类本身中,而不存在于ValueFilter的实例中。

相关问题