C#使用struct存储用户信息时编辑功能报错问题求助
问题根因及修复方案
核心报错原因
你定义的person是值类型(struct),List<person>的索引器返回的是值的临时副本,直接修改副本的属性不会对集合内的原始数据生效,C#编译器会直接抛出编译错误。
其他逻辑缺陷
除了值类型的问题,现有代码还有多处逻辑错误:
while(true)是死循环,字段选择变量ed1只在进入循环前读取一次,无法重复选择修改字段或者触发退出- 手机号、地址对应的case4、case5提示文案错误,均提示为"Enter Your Name"
- 退出逻辑中的
exm变量永远为false,永远不会触发退出,直接调用Main()还会存在递归栈溢出风险 - 匹配到目标用户后没有终止外层遍历,会继续无效循环
- ID修改的case1没有实现对应逻辑
修复方案
方案1(推荐):将person改为引用类型
把struct person改为class person,List中存储的是对象引用,直接修改info[i]的属性即可生效,这是业务实体类的常规实现方式,改动最小。
方案2(保留struct的情况)
如果必须用struct,修改属性时需要先取出临时变量,修改完成后再赋值回集合对应位置,示例:
person temp = info[i]; temp.name = Console.ReadLine(); info[i] = temp;
修复后完整Edit方法代码
这里以推荐的class方案为例,同时修复所有逻辑问题:
class person // 原struct改为class { public int id; public long phone; public string name, family, add; public void Show() { Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", id, name, family, phone, add); } } class Program { static List<person> info = new List<person>(); static void Edit() { Display(); Console.Write("Choose your target ID:"); int ed = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < info.Count; i++) { if (ed == info[i].id) { while (true) { // 每次循环重新提示选择操作 Console.WriteLine("1.ID\n2.Name\n3.FamilyName\n4.PhoneNumber\n5.Address\n6.Exit to menu"); Console.WriteLine("Which part of the user info would you like to update:"); int ed1 = Convert.ToInt32(Console.ReadLine()); switch (ed1) { case 1: Console.Write("Enter New ID:"); info[i].id = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("ID updated successfully"); break; case 2: Console.Write("Enter Your Name:"); info[i].name = Console.ReadLine(); Console.WriteLine("Name updated successfully"); break; case 3: Console.Write("Enter Your FamilyName:"); info[i].family = Console.ReadLine(); Console.WriteLine("FamilyName updated successfully"); break; case 4: Console.Write("Enter Your PhoneNumber:"); info[i].phone = Convert.ToInt64(Console.ReadLine()); Console.WriteLine("PhoneNumber updated successfully"); break; case 5: Console.Write("Enter Your Address:"); info[i].add = Console.ReadLine(); Console.WriteLine("Address updated successfully"); break; case 6: // 直接返回上一级菜单,避免递归调用Main导致栈溢出 return; default: Console.WriteLine("Invalid Operation, please try again"); break; } } } } // 补充未匹配到目标ID的提示 Console.WriteLine("Target ID not found"); } }
内容的提问来源于stack exchange,提问作者Reza Rezaee
相关产品推荐
相关产品推荐

