我有一个接口(IAnimal
),它由两个类Bear和Goat实现。如何将List <Bear>或List <Goat>分配到列表<IAnimal>
在运行时,我可能最终会与熊,或山羊的名单,但无论是他们需要被分配到财产IEnumerable<IAnimal>
这工作,为IEnumerable
共同变种。
不过,我现在需要从IEnumerable<IAnimal>
这当然行不通删除项目。
什么我需要做的,能够删除的项目?
这里是工作示例:
interface IAnimal {}
public class Bear : IAnimal {}
public class Goat : IAnimal {}
class Program
{
public static IEnumerable<IAnimal> CouldBeBearsOrGoats { get; set; }
static void Main(string[] args) {
var list = new List<int>() {1, 2, 3};
var bears = from l in list select new Bear();
var goats = from l in list select new Goat();
CouldBeBearsOrGoats = bears;
CouldBeBearsOrGoats = goats;
//How do I now remove an item?
}
}
如果我改变CouldBeBearsOrGoats到列表,然后我就可以删除项目,但我不能再分配任一类型。
public static List<IAnimal> CouldBeBearsOrGoats { get; set; }
该列表将会很长,所以我不想仅复制列表并使用副本。我正在做的是处理列表中的每个项目,然后删除它,直到列表为空。
@TimSchmelter,一个'列表'不是'ICollection的',所以它不会解决任何问题 –
通过提供'名单',你允许用户在山羊添加到熊的列表,这可能在您的系统中无效。如果你只想允许删除,也许你应该提供类似'IEnumerable Animals {get {return _animals.AsReadOnly(); }}'和'void RemoveAnimal(IAnimal animal){_animals.Remove(animal); }'。 –
nmclean