【发布时间】:2015-07-05 01:02:57
【问题描述】:
我不知道为什么我不能通过我已经接口的类遍历列表。
例如。
public interface IAnimal
{
string Name { get; set; }
}
public class Chicken:IAnimal
{
public string Name { get; set; }
}
public class Dog:IAnimal
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var AnimalList = new List<IAnimal>();
var Chicken1= new Chicken() { Name = "Chicken" };
var Dog1= new Dog() { Name = "Dog" };
AnimalList.Add(Dog1);
AnimalList.Add(Chicken1);
foreach (Dog obj in AnimalList)
{
Console.WriteLine(obj.Name);
}
}
}
我是不是做错了什么,有没有更好的角度来处理这种情况。
【问题讨论】:
-
你真的没有解释这段代码出了什么问题。
-
我可能正在阅读您的问题,但如果您尝试仅在循环中点击 Dog 对象,则对其进行过滤。
foreach (Dog obj in AnimalList.OfType<Dog>())
标签: c# list interface iteration