在LinkedList中搜索自定义Customer对象时遇CS1503错误的解决方法
解决LinkedList按电话号码查找并删除节点的CS1503错误
错误原因
LinkedList<Customer>.Find()方法要求传入Customer类型的对象,但你传入了字符串类型的电话号码,类型不匹配直接触发CS1503编译错误。这个方法默认通过对象引用或Equals()方法判断匹配,无法直接根据对象的某个属性(比如Phone)查找。
两种可行解决方法
方法一:手动遍历链表查找匹配节点
直接遍历customerList的所有节点,检查每个节点的Phone属性是否与输入的电话号码一致,找到后即可删除节点。
修改后的searchCustomerDetail方法(注意修正原方法的拼写错误):
public static void searchCustomerDetail() { Console.WriteLine("Please enter contact number!!"); Console.WriteLine(""); Console.Write("Contact number: "); string inputPhone = Console.ReadLine(); // 遍历链表查找匹配Phone的节点 LinkedListNode<Customer> targetNode = null; foreach (var customer in customerList) { if (customer.Phone == inputPhone) { targetNode = customerList.Find(customer); break; } } if (targetNode != null) { Console.WriteLine($"找到匹配客户:{targetNode.Value.Name}"); customerList.Remove(targetNode); // 删除找到的节点 Console.WriteLine("已删除该客户记录"); } else { Console.WriteLine("未找到对应电话号码的客户"); } }
方法二:重写Customer的Equals和GetHashCode方法
通过重写Customer类的Equals()和GetHashCode()方法,让系统认为Phone属性相同的Customer对象是相等的,这样就可以创建一个临时Customer对象传入Find()方法进行查找。
步骤1:重写Customer类的Equals和GetHashCode
public class Customer { public string Name { get; set; } public string Phone { get; set; } public string Payment { get; set; } public int[] Screening { get; set; } public static LinkedList<Customer> customerList = new LinkedList<Customer>(); // 重写Equals方法,按Phone判断对象相等 public override bool Equals(object obj) { if (obj is Customer otherCustomer) { return string.Equals(this.Phone, otherCustomer.Phone, StringComparison.OrdinalIgnoreCase); } return false; } // 重写GetHashCode,与Equals逻辑保持一致 public override int GetHashCode() { return Phone?.GetHashCode(StringComparison.OrdinalIgnoreCase) ?? 0; } // 原有addCustomerDetail、insert等方法... }
步骤2:修改查找方法
public static void searchCustomerDetail() { Console.WriteLine("Please enter contact number!!"); Console.WriteLine(""); Console.Write("Contact number: "); string inputPhone = Console.ReadLine(); // 创建临时Customer对象,仅设置Phone属性用于匹配 Customer tempCustomer = new Customer { Phone = inputPhone }; LinkedListNode<Customer> targetNode = customerList.Find(tempCustomer); if (targetNode != null) { Console.WriteLine($"找到匹配客户:{targetNode.Value.Name}"); customerList.Remove(targetNode); // 删除节点 Console.WriteLine("已删除该客户记录"); } else { Console.WriteLine("未找到对应电话号码的客户"); } }
额外提示
- 原代码中
searchCunstomerDetail存在拼写错误(应为searchCustomerDetail),建议修正避免后续维护问题。 - 可以增加用户输入的合法性校验(比如电话号码格式检查),提升程序健壮性。
内容的提问来源于stack exchange,提问作者Taewan Vitooreangrong
相关产品推荐
相关产品推荐

