C#中多动物类集合的变量访问及代码优化方案咨询
解决方案
方案1:基类定义抽象属性,派生类按需实现(推荐)
通过给基类定义统一的抽象属性,让每个派生类根据自身特性实现对应属性,不需要的属性直接返回0,这样集合可以直接声明为ObservableCollection<AnimalTypes>,遍历的时候能直接访问所有属性,且无空置变量。
代码示例
首先定义基类和派生类:
public abstract class AnimalTypes { // 定义所有需要访问的抽象属性 public abstract int NoOfLegs { get; } public abstract int NoOfWings { get; } } // 哺乳动物派生类 public class Mammal : AnimalTypes { public override int NoOfLegs { get; } = 4; public override int NoOfWings { get; } = 0; // 无翅膀返回0 } // 鸟类派生类 public class Bird : AnimalTypes { public override int NoOfLegs { get; } = 2; public override int NoOfWings { get; } = 2; } // 蛇类派生类 public class Snake : AnimalTypes { public override int NoOfLegs { get; } = 0; public override int NoOfWings { get; } = 0; }
然后使用ObservableCollection存储并访问:
var animalCollection = new ObservableCollection<AnimalTypes>(); animalCollection.Add(new Mammal()); animalCollection.Add(new Bird()); animalCollection.Add(new Snake()); // 遍历访问属性 foreach (var animal in animalCollection) { Console.WriteLine(animal.NoOfLegs); Console.WriteLine(animal.NoOfWings); }
方案2:使用模式匹配遍历集合
如果无法修改原有基类和派生类结构,可以在遍历的时候通过模式匹配判断对象类型,访问对应变量,不存在的变量返回0。
代码示例
假设原有类结构如下:
public class AnimalTypes { } public class Mammal : AnimalTypes { public int NoOfLegs = 4; } public class Bird : AnimalTypes { public int NoOfLegs = 2; public int NoOfWings = 2; } public class Snake : AnimalTypes { // 无腿和翅膀变量 }
遍历逻辑:
var animalCollection = new ObservableCollection<AnimalTypes>(); animalCollection.Add(new Mammal()); animalCollection.Add(new Bird()); animalCollection.Add(new Snake()); foreach (var animal in animalCollection) { // 通过模式匹配获取腿的数量 int legs = animal switch { Mammal m => m.NoOfLegs, Bird b => b.NoOfLegs, _ => 0 }; // 通过模式匹配获取翅膀的数量 int wings = animal switch { Bird b => b.NoOfWings, _ => 0 }; Console.WriteLine(legs); Console.WriteLine(wings); }
方案3:扩展方法封装访问逻辑
把类型判断和属性获取的逻辑封装到扩展方法中,让遍历代码更简洁,同时集中管理判断逻辑。
代码示例
public static class AnimalExtensions { public static int GetNoOfLegs(this AnimalTypes animal) { return animal switch { Mammal m => m.NoOfLegs, Bird b => b.NoOfLegs, _ => 0 }; } public static int GetNoOfWings(this AnimalTypes animal) { return animal switch { Bird b => b.NoOfWings, _ => 0 }; } }
遍历调用:
foreach (var animal in animalCollection) { Console.WriteLine(animal.GetNoOfLegs()); Console.WriteLine(animal.GetNoOfWings()); }
内容的提问来源于stack exchange,提问作者nb-1999
相关产品推荐
相关产品推荐

