如何为C#单链表实现无参Sum()方法?求解决方案
链表求和问题的解决方案
你的代码存在两个核心问题导致无法调用Sum():
Append方法返回的是Strategy抽象类类型,而Sum()仅定义在Add子类中,编译时无法直接调用- 原代码存在语法错误:
new Add(5))多了一个右括号,new add(15)中的类名应为大写Add
以下是几种可行的解决方案:
方案一:抽象类定义求和接口,子类实现(推荐)
在抽象类Strategy中添加抽象的Sum()方法,让子类实现具体求和逻辑。这种方式符合面向对象设计原则,扩展性强。
修改后的完整代码:
void Main() { // 修正语法错误 var chain1 = new Add(5).Append(new Add(10)).Append(new Add(15)); var sum = chain1.Sum(); Console.WriteLine(sum); // 输出30 } public abstract class Strategy { protected Strategy _next; // 改为protected,允许子类访问 public Strategy Append(Strategy next) { if (_next == null) { _next = next; } else { _next.Append(next); } return this; } // 定义抽象求和方法 public abstract int Sum(); } public class Add : Strategy { int _num; public Add(int num) => _num = num; public override int Sum() { // 递归计算:当前节点数值 + 后续节点总和(无后续则加0) return _num + (_next?.Sum() ?? 0); } }
方案二:类型转换调用(仅临时应急)
如果不想修改抽象类结构,可以将Strategy类型强制转换为Add类型后调用Sum(),但仅适用于链表所有节点都是Add类型的场景,扩展性差。
void Main() { var chain1 = new Add(5).Append(new Add(10)).Append(new Add(15)); var sum = ((Add)chain1).Sum(); Console.WriteLine(sum); } public abstract class Strategy { protected Strategy _next; // 改为protected,允许Add类访问 public Strategy Append(Strategy next) { if (_next == null) { _next = next; } else { _next.Append(next); } return this; } } public class Add : Strategy { int _num; public Add(int num) => _num = num; public int Sum() { int total = _num; Strategy current = _next; // 遍历链表累加数值 while (current != null) { total += ((Add)current)._num; current = current._next; } return total; } }
方案三:扩展方法实现求和
给Strategy类添加扩展方法,通过遍历链表计算总和,无需修改原有类的核心逻辑。
void Main() { var chain1 = new Add(5).Append(new Add(10)).Append(new Add(15)); var sum = chain1.CalculateSum(); Console.WriteLine(sum); } public abstract class Strategy { private Strategy _next; public Strategy Append(Strategy next) { if (_next == null) { _next = next; } else { _next.Append(next); } return this; } // 公开方法获取下一个节点 public Strategy GetNext() => _next; } public class Add : Strategy { public int Num { get; } // 公开数值属性供扩展方法访问 public Add(int num) => Num = num; } // 扩展方法类 public static class StrategyExtensions { public static int CalculateSum(this Strategy head) { int total = 0; Strategy current = head; while (current != null) { if (current is Add addNode) { total += addNode.Num; } current = current.GetNext(); } return total; } }
内容的提问来源于stack exchange,提问作者dtk77
相关产品推荐
相关产品推荐

