如何从传入的串行数据中自动将项目添加到列表中?

How to auto-add item to a list from an incoming serial data?

我正在尝试使用 c# 和 GMap.net 跟踪对象的实时位置。在 GMap.net 中,为了追踪路线,我必须使用 List<PointLatLng>,然后使用 Pen 统一它们。

问题是一开始我不知道对象会在哪里,所以我没有要添加的点,第一个部分。

是否可以在列表中只添加一个点并实时更新?

或者,可以将第一个点保存到一个变量中,然后使用先前变量的名称添加其他点,每次从串行端口接收到数据时将数字递增 1,然后刷新列表新点?

`

List<PointLatLng> points = new List<PointLatLng>();
var coordinates = new List<PointLatLng> { new PointLatLng(GPS_Latitude, GPS_Longitude) };
coordinates.Add(new PointLatLng(GPS_Latitude, GPS_Longitude));
GMapOverlay trace = new GMapOverlay("Real Time Position");
GMapRoute carroute = new GMapRoute(coordinates, "Traiectory");
gMapControl1.Overlays.Add(trace);
trace.Routes.Add(carroute);
//Pen redPen = new Pen(Color.Red, 3);
carroute.Stroke = new Pen(Color.Red, 3);

`

这样我只有第一点没有其他的。串口以 1hz 的频率接收数据。我的意思是:即使我收到超过 1 个数据,列表也只计算一个项目而不是更多。

这些解决方案中的任何一个都是可行的。


你可以有一个点列表,然后在你想向列表中添加一个点时调用 .Add()(如果你只是保存一个点 - 如果是这种情况,请参见下一个示例)。这样你就有了所有点的历史。您始终可以通过访问列表中最后一个索引处的项目来获取最新点:

// Create list and (optionally) add the first point to it
var points = new List<Point> { new Point(x, y) };

// Add a new point to the list whenever you want
points.Add(new Point(newX, newY));

// Get the most recent point by getting the item at the last index
var newestPoint = points[points.Count - 1];  // Note: this will fail if the list is empty

您也可以有一个点变量,然后通过独立更改值或为其分配一个新点来更新它的坐标:

var myPoint = new Point(x, y);

// Update coordinates independently whenever you want
myPoint.X = newX; 
myPoint.Y = newY;

// Or just assign a new Point
myPoint = new Point(newX, newY);