C#字典读写问题:打印首个元素报错,提示int无法转string
解决C# Dictionary读取首个添加元素的问题
你的代码报错是因为C#的Dictionary<TKey, TValue>不支持数字索引访问,它的索引器要求传入与键类型一致的参数(这里是string类型的姓名),而你传入int类型的0,类型不匹配导致编译错误。
下面提供两种解决方式:
方式1:直接通过已知键访问(推荐)
既然你明确知道首个添加的键是"John Doe",直接用这个键访问对应值即可,这也是Dictionary设计的核心用法:
using System; using System.Collections.Generic; public class Program { public static void Main() { Dictionary<string, int> people = new Dictionary<string, int>(); people.Add("John Doe", 23); people["John Foe"] = 27; // 直接用首个添加的键获取值并打印 Console.WriteLine($"姓名:John Doe,年龄:{people["John Doe"]}"); } }
方式2:动态获取首个元素(依赖插入顺序)
如果你需要动态获取首个插入的元素,可借助LINQ的First()方法,但要注意版本限制:
- 在.NET Framework、.NET Core 2.x及更早版本中,Dictionary不保证元素顺序,
First()返回的结果可能不是你插入的第一个元素; - 从.NET Core 3.0/.NET 5开始,Dictionary会保留插入顺序,此时
First()会返回你第一个添加的元素。
代码示例:
using System; using System.Collections.Generic; using System.Linq; // 需引入LINQ命名空间 public class Program { public static void Main() { Dictionary<string, int> people = new Dictionary<string, int>(); people.Add("John Doe", 23); people["John Foe"] = 27; // 获取首个键值对并打印 var firstPerson = people.First(); Console.WriteLine($"姓名:{firstPerson.Key},年龄:{firstPerson.Value}"); } }
内容的提问来源于stack exchange,提问作者Alejandro Pedraza
相关产品推荐
相关产品推荐

