C#中创建包含类实例的List遇问题,求错误排查及正确实现方法
代码错误分析与修复
存在的问题
- 非静态成员无法在静态
Main方法中直接访问:bird、duck、crow、canary以及birdArray都是Program类的实例字段,而Main是静态方法,静态方法只能访问静态成员,或创建类实例后访问实例成员。 - List长度判断错误:List集合的元素数量属性是
Count,Length是数组类型的专属属性,不能用于List。
修复后的代码
using System; using System.Collections.Generic; class Bird { private string _name; public string Name { get { return _name; } set { _name = value; } } public Bird() { _name = "Bird"; } public virtual string makeSound() { return "Chirp"; } } class Duck : Bird { public override string makeSound() { return "Quack"; } } class Crow : Bird { public override string makeSound() { return "Squawk"; } } class Canary : Bird { public override string makeSound() { return "Tweet"; } } class Program { public static void Main(string[] args) { // 在静态方法内创建实例并初始化List Bird bird = new Bird(); Bird duck = new Duck(); Bird crow = new Crow(); Bird canary = new Canary(); List<Bird> birdList = new List<Bird>(){bird, duck, crow, canary}; // 使用List的Count属性判断循环边界 for (int i=0; i < birdList.Count; i++) { Console.WriteLine(birdList[i].makeSound()); } // 也可以用foreach循环更简洁 foreach (Bird b in birdList) { Console.WriteLine(b.makeSound()); } } }
补充说明
- 将实例创建和List初始化放到
Main方法内部,规避静态方法访问非静态成员的问题。 - 用
Count替换Length来获取List的元素总数。 - 推荐使用
foreach循环遍历List,代码更简洁易读,无需手动维护索引。
内容的提问来源于stack exchange,提问作者kyupid_codes
相关产品推荐
相关产品推荐

