将列表类型转换为IEnumerable接口类型
我有一个
List personlist;
我怎样才能转换为
IEnumerable iPersonList
Person实现IPerson接口
如果您使用的是.NET 4.0或更高版本,则可以执行隐式转换:
IEnumerable iPersonList = personlist; //or explicit: var iPersonList = (IEnumerable )personlist;
这在IEnumerable
使用了通用的逆变 – 即因为你只从 IEnumerable
得到一些东西,你可以隐含地将IEnumerable
转换为IEnumerable
如果T : U
。 (它还使用List
。)
否则,您必须使用LINQ强制转换每个项目:
var iPersonList = personlist.Cast();
您可以使用IEnumerable.Cast
var iPersonList = personlist.Cast();
从.NET 4.0开始,您可以将List
传递给参数类型为IEnumerable
而无需隐式或显式转换。
由于逆转 ,隐式铸造是自动完成的(如果可能的话)
你可以这样做:
var people = new List(); // Add items to the list ProcessPeople(people); // No casting required, implicit cast is done behind the scenes private void ProcessPeople(IEnumerable people) { // Processing comes here }