将列表类型转换为IEnumerable接口类型

本文关键字:IEnumerable 接口类型 类型转换 列表 | 更新日期: 2023-09-27 18:00:55

我有一个

List<Person> personlist; 

如何转换为

IEnumerable<IPerson> iPersonList

Person实现IPerson接口

将列表类型转换为IEnumerable接口类型

如果您在。NET 4.0或更高版本,您只需执行隐式强制转换:

IEnumerable<IPerson> iPersonList = personlist;
//or explicit:
var iPersonList = (IEnumerable<IPerson>)personlist;

这在IEnumerable<out T>中使用了一般的逆变换——也就是说,因为你只从IEnumerable的中得到一些东西,所以如果T : U,你可以隐式地将IEnumerable<T>转换为IEnumerable<U>。(它也使用List<T> : IEnumerable<T>。(

否则,您必须使用LINQ:铸造每个项目

var iPersonList = personlist.Cast<IPerson>();

您可以使用IEnumerable.Cast

var iPersonList = personlist.Cast<IPerson>();

自。NET 4.0中,您可以将List<Person>传递给具有IEnumerable<IPerson>类型参数的方法,而无需隐式或显式强制转换。

隐式投射是自动完成的(如果可能的话(,这要归功于反方差

你可以这样做:

var people = new List<Person>();
// Add items to the list
ProcessPeople(people); // No casting required, implicit cast is done behind the scenes

private void ProcessPeople(IEnumerable<IPerson> people)
{
// Processing comes here
}