C# 将列表类型转换为 IEnumerable 接口类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15071828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert List Type to IEnumerable Interface Type
提问by patrick
I have a
我有一个
List<Person> personlist;
How can I convert to
我怎样才能转换为
IEnumerable<IPerson> iPersonList
Person Implements IPerson interface
Person 实现 IPerson 接口
采纳答案by Rawling
If you're in .NET 4.0 or later, you can just do an implicit cast:
如果您使用 .NET 4.0 或更高版本,则可以执行隐式转换:
IEnumerable<IPerson> iPersonList = personlist;
//or explicit:
var iPersonList = (IEnumerable<IPerson>)personlist;
This uses generic contravariance in IEnumerable<out T>
- i.e. since you only ever get something outof an IEnumerable
, you can implicitly convert IEnumerable<T>
to IEnumerable<U>
if T : U
. (It also uses that List<T> : IEnumerable<T>
.)
这使用了通用逆变 in IEnumerable<out T>
- ie 因为你只能从an 中得到一些东西IEnumerable
,你可以隐式转换IEnumerable<T>
为IEnumerable<U>
if T : U
。(它也使用那个List<T> : IEnumerable<T>
。)
Otherwise, you have to cast each item using LINQ:
否则,您必须使用 LINQ 转换每个项目:
var iPersonList = personlist.Cast<IPerson>();
回答by juharr
You can use the IEnumerable.Cast
您可以使用 IEnumerable.Cast
var iPersonList = personlist.Cast<IPerson>();
回答by domenu
Since .NET 4.0, you can pass List<Person>
to a method with a parameter of type IEnumerable<IPerson>
without implicit or explicit casting.
从 .NET 4.0 开始,您可以将List<Person>
类型参数传递给方法,IEnumerable<IPerson>
而无需隐式或显式转换。
Implicit casting is done automatically (if possible), thanks to contravariance
由于逆变,隐式转换是自动完成的(如果可能)
You can do this:
你可以这样做:
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
}