我有一個類Mobile,其中宣告了我的字典。我有另一個類Cell,我想通過它呼叫這個字典并向其中添加專案。我在Mobile類中創建了一個函式來將元素添加到字典中。我的兩個班是。
public class Mobile {
public Dictionary<string, Mobile> dict;
public Mobile(int x,int y) {
this.x=x;
this.y=y;
dict = new Dictionary<string, Mobile>();
}
pulic void Add_data_to_dictionary(string a,Mobile b)
{
this.dict.Add(a,b);
}
}
public class Cell
{
Mobile x=new Mobile():
}
我需要在 Cell 類中實作我的代碼。我的問題是我必須創建一個Mobile類的節點串列,其中每個節點必須包含一個字典,每個字典應該有多個鍵值對。
層次結構是這樣的
node1->dictionary[key1,val1,key2,val2]
node2->dictionary[key1,val1,key2,val2]
node3->dictionary[key1,val1,key2,val2]
誰能幫我我該怎么做?
uj5u.com熱心網友回復:
我仍然不確定你想要實作什么,但正如你所說:
我需要一個移動類串列。在 List 的每個索引處,我需要一個 Mobile 類的字典,其中每個字典可以有許多鍵值對條目。
它可能以這種方式完成:
class Program
{
static void Main(string[] args)
{
// Initialize List of your Mobiles
List<Mobile> mobiles = new List<Mobile>();
// Fill list in some way
for (int i = 0; i < 5; i )
{
// Create new Mobile
Mobile mobile = new Mobile();
// Add data to its Dictionary
mobile.AddDataToDictionary("SomeKey #" i, mobile); // Add itself as value?!
// Add to list of Mobiles (your nodes)
mobiles.Add(mobile);
}
// Create Cell instance and pass list of Mobiles to it
Cell cell = new Cell(mobiles);
// Do what you want with mobiles there
cell.DoWorkWithMobiles();
Console.ReadKey();
}
}
public class Mobile
{
// Make Dictionary as public property to grant access to it for read purposes
public Dictionary<string, Mobile> Dict { get; private set; }
// I removed arguments x/y for this example
public Mobile()
{
Dict = new Dictionary<string, Mobile>();
}
public void AddDataToDictionary(string key, Mobile value)
{
Dict.Add(key, value);
}
}
public class Cell
{
// To store list, which was passed to class constructor
private List<Mobile> mobiles;
public Cell(List<Mobile> mobiles)
{
this.mobiles = mobiles;
}
public void DoWorkWithMobiles()
{
// Very unclear what to do here
for (int i = 0; i < mobiles.Count; i )
{
Mobile mobile = mobiles[i];
Mobile mobileFromDict = mobile.Dict["SomeKey #" i];
//or
mobile.Dict.TryGetValue("SomeKey #" i, out Mobile mob);
Mobile m = mob.Dict["SomeKey #" i];
}
}
}
如您所見,您專案的架構和邏輯不清楚,示例可能不正確和愚蠢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/324845.html
上一篇:我已經使用串列作為每個鍵的值制作了一個字典,我想列印沒有方括號的值
下一篇:如何從字典串列中過濾并寫入檔案?
