目前,我正在開發一個由 200 個傳感器節點組成的網絡模擬器。在我的代碼中,我需要每個節點向其鄰居發送 hello 數據包。在上一步中,我編寫了一段代碼,將 hello 消息從特定節點廣播到其鄰居(它們是傳感器節點)?,F在,我需要這些傳感器節點將其隊列中的 hello 數據包重新轉發給其鄰居。我需要檢查傳感器節點的隊列是否已經有一個 hello 數據包,以便將其重新轉發到該傳感器節點的鄰居。。。例如,我創建了這樣的 hello : Packet hello = new Packet(CNs[i].cnID, i, i, 0, CNs[i].cnDepth, DateTime.Now, "Hello, I am a Courier node near of you");數據包聲明如下:using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace AUV_Topology{ class Packet { public int senderID; public int nextID; public int recieverID; public int packetSequenceNum; public int depth; public DateTime sendingTime; public String data; public Packet(int sID, int nID, int rID, int pSecNum, int depth,DateTime sTime, String data) { this.senderID = sID; this.nextID = nID; this.recieverID = rID; this.packetSequenceNum = pSecNum; this.depth = depth; this.sendingTime = sTime; this.data = data; } }}為了確保傳感器節點隊列有從另一個節點收到的 hello 數據包,我使用“foreach”并檢查列表中的每個數據包是否包含“Hello,我是您附近的 Courier 節點”...不幸的是,我嘗試使用SNs[i]queue.contains("Hello, I am a Courier node near of you");其中SN[i]是傳感器節點數組,隊列是聲明如下的屬性:public List<Packet> queue = new List<Packet>();但我收到語法錯誤:參數 1:無法從“string”轉換為“AUV_Topology.Packet”AUVs_TOPOLOGY我怎樣才能做到這一點?這是一個可能的解決方案嗎: for(int j=0; j < NodeNum; j++) { if (SNsNighbors[i, j] == 1) { String temp = SNs[i].queue.ToString(); if (temp.Contains("Hello")) { } } }
1 回答

慕姐4208626
TA貢獻1852條經驗 獲得超7個贊
如果queue
是數據包列表,并且您想知道這些數據包中是否有一個data
是 hello 消息,請確保您已導入 LINQ 并執行以下操作:
SNs[i].queue.Any(pkt => pkt.data == "Hello, I am a Courier node near of you");
如果任何數據包具有該數據,則返回 bool true。如果要檢索包含此數據的第一個數據包,請將 Any 替換為 First。如果多個數據包都有它并且您希望所有數據包都將其交換為Where
附:在 C# 中,我們以首字母大寫字母命名公共成員,例如 Data、Queue 等,并且我們更喜歡公共屬性而不是公共變量。此外,如果使用 FIFO 隊列來建模隊列更合適,則 System.Collections.Generic 命名空間與 List 一起具有其中之一
- 1 回答
- 0 關注
- 131 瀏覽
添加回答
舉報
0/150
提交
取消