使用Console.ReadLine填充ArrayList时报错,有哪些可行的解决方法?
问题原因
- 你的代码报错是因为
ArrayList.Add()方法的调用语法错误:该方法需要将待添加的元素作为参数传入括号内部,不能对Add()的返回值做赋值操作,且ArrayList.Add()本身返回值为void,本身不支持被赋值。
修正后的实现方案
1. 沿用ArrayList的正确写法
using System; using System.Collections; class Program { static void Main(string[] args) { ArrayList names = new ArrayList(); // 将Console.ReadLine()作为参数传入Add方法即可 names.Add(Console.ReadLine()); names.Add(Console.ReadLine()); names.Add(Console.ReadLine()); } }
2. 更推荐的泛型集合实现
ArrayList属于非泛型集合,已经不推荐在新版本C#中使用,你可以用类型更安全的List<string>替代,避免后续操作时的类型转换开销:
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<string> names = new List<string>(); // 如果需要固定录入3条,可以用循环简化代码 for (int i = 0; i < 3; i++) { // 加??判空可以避免用户直接回车输入null的情况 names.Add(Console.ReadLine() ?? string.Empty); } } }
内容的提问来源于stack exchange,提问作者OnlyProblems
相关产品推荐
相关产品推荐

