简体   繁体   中英

How to properly add new items to a collection?

Here I am trying to store loads of datapoints of the custom WindDataPoint type.

However, I recently found out that the whole time, my code has been creating tens of thousands of duplicate data points. The data points change to the latest value, yes, but instead of adding a new datapoint, it sets ALL datapoints to that value as well.

Here is the code of concern:

    private void Timer_Data_Tick(object sender)
    {
        if (!Timer_Data_Enabled)
            return;
        for (int i = 0; (itsDAQ.getStreamCount() > 0) && (i < 6); i++)
        {
            WindDAQ.WindDataPoint thisDataPoint = new      WindDAQ.WindDataPoint();
            thisDataPoint = itsDAQ.getValue(Recording);
            dataPointCollection.Add(thisDataPoint);
            newChartPoint = true;
        }

    }

Here is the code for getValue() and getValue(bool record)

    //Get Real-world values
    public WindDataPoint getValue()
    {
        holdDequeueValue = DAQStream.Dequeue();
        holdWindDataPoint.Lift = Lift_Sensor.getForce(holdDequeueValue[ChannelOutOrder[0]]);
        holdWindDataPoint.Drag = Drag_Sensor.getForce(holdDequeueValue[ChannelOutOrder[1]]);
        holdWindDataPoint.Velocity = Pitot_Sensor.getVelocity(holdDequeueValue[ChannelOutOrder[2]]);
        holdWindDataPoint.isRecorded = false;

        //This translates the number of samples since start into actual time since start
        //Why not get current time? I don't want the current time. I want the time the sample was taken.
        holdWindDataPoint.Time = SamplesToTime(SamplesReadSinceStart); 
        SamplesReadSinceStart++;
        return holdWindDataPoint;
    }

    //Get Read-world values and set whether the sample is recorded.
    public WindDataPoint getValue(bool record)
    {
        getValue();
        holdWindDataPoint.isRecorded = record;
        return holdWindDataPoint;
    }
  1. You shouldn't be instantiating thisDataPoint if you're only going to redefine it after.
  2. getValue is returning a reference to the same object every time. This means that you will always see the same data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM