簡體   English   中英

如何從傳入的串行數據自動將項目添加到列表?

[英]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() (如果只保存一個點,則使用List毫無意義-如果是這種情況,請參見下一個示例)。 這樣,您便擁有了所有要點的歷史。 您始終可以通過訪問列表中最后一個索引處的項目來獲取最新點:

// 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM