我有一个
List<Person> personlist;
如何转换为
IEnumerable<IPerson> iPersonList
Person实现IPerson接口
如果您在。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
}