I have created a simple class to filter out data from a data stream. The problem is that if I use more than one ValueFilter object, they all use the same queue. I want there to be a separate queue for each ValueFilter Object. I am declaring the ValueFilter in my main program like this: ValueFilter filter = new ValueFilter();
Should I be using some kind of constructor?
using System;
using Microsoft.SPOT;
using System.Collections;
namespace foo
{
class ValueFilter
{
private const int FILTER_QUEUE_SIZE = 10;
priva开发者_如何学编程te 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;
}
}
Since the Queue seems to be private, all you need to do is remove the static
modifier:
//private static int sum = 0;
//private static Queue queue = new Queue();
private int sum = 0;
private Queue queue = new Queue();
Now every ValueFilter instance has its own sum
and queue
instances. A non-static member is an instance member.
You're declaring your Queue variable as static
. If you want one Queue per FilterValue, don't use a static queue, use an instance variable for it.
You declared "queue" as static, therefore it exists in the class ValueFilter itself and not in instances of ValueFilter.
精彩评论