如何在C#中创建内含字典的Mobile类实例列表并通过Cell类操作字典添加数据
解决方案
先纠正你代码里的几个小问题,不然编译会报错:
- Mobile类里的
pulic拼写错误,应该是public - Mobile的构造函数需要传入两个int参数,Cell里直接
new Mobile()会报错,必须传值 - Mobile类里的
x、y字段没有声明,得先定义出来
修正后的Mobile类
public class Mobile { // 先声明x、y字段 public int x, y; public Dictionary<string, Mobile> dict; public Mobile(int x, int y) { this.x = x; this.y = y; dict = new Dictionary<string, Mobile>(); } // 修正拼写错误的public public void Add_data_to_dictionary(string a, Mobile b) { this.dict.Add(a, b); } }
Cell类的实现(完成你的需求)
在Cell类里,我们可以创建一个List<Mobile>来存储所有节点,然后逐个创建Mobile实例,再给每个实例的字典添加多组键值对:
public class Cell { // 用来存储所有Mobile节点的列表 public List<Mobile> MobileNodes { get; set; } public Cell() { MobileNodes = new List<Mobile>(); // 创建node1,并给它的字典添加键值对 Mobile node1 = new Mobile(1, 1); // 添加key1对应的Mobile实例 node1.Add_data_to_dictionary("key1", new Mobile(10, 10)); // 添加key2对应的Mobile实例 node1.Add_data_to_dictionary("key2", new Mobile(20, 20)); MobileNodes.Add(node1); // 创建node2,同理添加键值对 Mobile node2 = new Mobile(2, 2); node2.Add_data_to_dictionary("key1", new Mobile(30, 30)); node2.Add_data_to_dictionary("key2", new Mobile(40, 40)); MobileNodes.Add(node2); // 创建node3,添加键值对 Mobile node3 = new Mobile(3, 3); node3.Add_data_to_dictionary("key1", new Mobile(50, 50)); node3.Add_data_to_dictionary("key2", new Mobile(60, 60)); MobileNodes.Add(node3); } }
验证方式
如果你想测试是否符合需求,可以在主程序里这样调用:
Cell cell = new Cell(); // 遍历每个节点,输出它的字典内容 foreach (var node in cell.MobileNodes) { Console.WriteLine($"节点坐标:({node.x}, {node.y})"); foreach (var kvp in node.dict) { Console.WriteLine($" {kvp.Key} -> 对应Mobile坐标:({kvp.Value.x}, {kvp.Value.y})"); } }
这样就能得到你想要的层级结构:每个node都有自己的字典,字典里包含多组key-value(value是Mobile实例)。
内容的提问来源于stack exchange,提问作者RA FI
相关产品推荐
相关产品推荐

