我理解前两个陈述。但是,对于第三个陈述,我无法弄清楚这是什么类型的人? IEnumerable(人)或List(人)?我假设幕后有转换。有人可以解释声明3中使用的技术吗?
答案 0 :(得分:10)
IEnumerable<Person> people = new IEnumerable<Person>();
无效。 IEnumerable
是接口,无法实例化。
第二个是有效的:
List<Person> people = new List<Person>();
IEnumerable<Person> people = new List<Person>();
上面的第二个例子只是将集合转换为IEnumerable<Person>
。这意味着List
提供的功能不可用,除非您将集合强制转换为列表。简而言之,这并不是那么有用。在定义方法时,转换为IEnumerable
非常有用:
void DoSomethingWithPeople(IEnumerable<Person> people)
{
foreach(var person in people)
Console.WriteLine(person.Name);
}
在这里,我们不关心集合是列表,集合,链表等。我们关心的是people
可以被枚举的事实(也就是说,它是枚举)。
答案 1 :(得分:0)
您确实需要区分类型的参考和实际的对象类型。看看这个:
真实用例,如果你真的需要只根据动物的number of feet
来处理某些东西,那么你可以将Animal
引用传递给以Animal为参数的方法,而真正的对象是Animal myDogAsAnimal = new Dog();
或Animal myOstrichAsAnimal = new Ostrich();
但是,如果不转换Dog
Ostrich
和(myOstrichAsAnimal as Ostrich).BuryHeadInGround();
的属性和方法
class Program
{
static void Main(string[] args)
{
int convertingChartToInt = 'A'; // Valid - Covert Chart to int and store it in this variable.
int covertDecimalToString = 5.0m; // Invalid - Convert Decimal to String and Store it in this variable.
ICollection<String> covertListToICollection = new List<string>(); // Valid List<T> Implements ICollection<T>
List<Animal> animals = new List<Animal>();
List<Dog> myDogs = new List<Dog>();
Animal myOstrichAsAnimal = new Ostrich();
Animal myDogAsAnimal = new Dog();
Dog myDogAsDog = new Dog();
myOstrichAsAnimal.BuryHeadInGround(); // Will not Compile
(myOstrichAsAnimal as Ostrich).BuryHeadInGround(); // Will Compile
myDogAsAnimal.Bark(); // Will Not Compile
myDogAsDog.Bark(); // Will Compile
AdapotAnimal(myOstrichAsAnimal); // Will Compile
animals.Add(myOstrichAsAnimal); // Will Compile
animals.Add(myDogAsAnimal); // Will Compile
animals.Add(myDogAsDog); // Will Compile
FeedAnimals(animals); // Will Compile
}
private static void AdapotAnimal(Animal animal)
{
}
private static void FeedAnimals(List<Animal> animals)
{
}
}
public class Animal
{
public int NumberOfFeet { set; get; }
}
public class Ostrich : Animal
{
public void BuryHeadInGround()
{
}
}
public class Dog : Animal
{
public void Bark()
{
}
}
答案 2 :(得分:-1)
这是面向对象编程的基础。
IEnumerable是一个接口。它定义方法而不实现它们。
List是一个类并实现IEnumerable。这意味着它提供了接口方法的实现。您可以有多个接口实现。
你的第二个语句无论如何都不会起作用,因为你不能创建一个接口的实例(一个对象),只能是一个具体的类。
请阅读一些有关接口和oop的基本书籍或教程
答案 3 :(得分:-3)
这会将您的角色对象放入班级人员的新列表中。