C# 无法将 List<T> 隐式转换为 Collection<T>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/524428/
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
Cannot implicitly convert List<T> to Collection<T>
提问by Valentin Vasilyev
This is a compiler error (slightly changed for readability).
这是一个编译器错误(为了可读性略有改变)。
This one always puzzled me. FxCop tells that this is a bad thing to return List and classes that are\derived from Collection<T>
should be preferrable as return types.
这个一直让我很困惑。FxCop 告诉我们返回 List 是一件坏事,并且派生自的类Collection<T>
应该更适合作为返回类型。
Also, FxCop says that it is OK to use List<T>
for internal data storage\manipulation.
Ok, I get it, but what I don't get is that compiler complains about trying to implicitly convert List<T>
to Collection<T>
. Isn't List<T>
more interface-charged and functional?
Why prohibit implicit conversion?
此外,FxCop 表示可以List<T>
用于内部数据存储\操作。好的,我明白了,但我不明白的是编译器抱怨试图隐式转换List<T>
为Collection<T>
. 不是List<T>
更多的接口充电和功能吗?为什么禁止隐式转换?
And another question that stems from above: is new List<int>(some collection<int>)
constructor expensive?
另一个来自上面的问题:new List<int>(some collection<int>)
构造函数昂贵吗?
Thank you,
谢谢,
Valentin Vasiliev
瓦伦丁·瓦西里耶夫
采纳答案by Jon Skeet
List<T>
doesn't derive from Collection<T>
- it does, however, implement ICollection<T>
. That would be a better choice of return type.
List<T>
不派生自Collection<T>
- 然而,它实现了ICollection<T>
. 那将是返回类型的更好选择。
As for the new List<int>(some collection<int>)
question - it partly depends on what the collection is. If it implements ICollection<T>
(at execution time) then the constructor can use its Count
property to create the list with the right initial capacity before iterating through it and adding each item. If it doesn't implement ICollection<T>
then it's just equivalent to:
至于new List<int>(some collection<int>)
问题 - 这部分取决于收藏品是什么。如果它实现了ICollection<T>
(在执行时),那么构造函数可以使用它的Count
属性来创建具有正确初始容量的列表,然后再遍历它并添加每个项目。如果它没有实现,ICollection<T>
那么它就相当于:
List<int> list = new List<int>();
foreach (int x in otherCollection)
{
list.Add(x);
}
Still nice to have in a convenient constructor, but not hugely efficient - it can't be, really.
在一个方便的构造函数中仍然很好,但效率不高——它不可能,真的。
I don't believe the constructor does anything cunning for arrays, which it potentially could - using Array.Copy
or whatever to just copy the lot in one go rather than iterating though. (Likewise if it were another List<T>
it could get at the backing array and copy that directly.)
我不相信构造函数对数组做任何狡猾的事情,它可能会 - 使用Array.Copy
或任何方式一次性复制批次而不是迭代。(同样,如果它是另一个,List<T>
它可以获取支持数组并直接复制它。)
回答by David Morton
List<T>
doesn't inherit from Collection<T>
. Plain and simple. Unless List<T>
provides an operator to implicitly convert to/from Collection<T>
, you can't do it. I would actually suggest returning List<T>
if you can, as I believe the rules go something like this:
List<T>
不继承自Collection<T>
. 干净利落。除非List<T>
提供一个运算符来隐式转换为/从Collection<T>
,否则你不能这样做。List<T>
如果可以的话,我实际上建议返回,因为我相信规则是这样的:
Accept as a parameter the least constrictive interface possible. Return as a return parameter the most constrictive type possible.
接受尽可能少的限制接口作为参数。将最严格的类型作为返回参数返回。
回答by David Morton
Here is a generic extension method written in C# 3.0 used to convert List<T>
to Collection<T>
下面是一个用 C# 3.0 编写的通用扩展方法,用于转换List<T>
为Collection<T>
using System.Collections.Generic;
using System.Collections.ObjectModel;
public static class ExtensionMethods
{
public static Collection<T> ToCollection<T>(this List<T> items)
{
Collection<T> collection = new Collection<T>();
for (int i = 0; i < items.Count; i++)
{
collection.Add(items[i]);
}
return collection;
}
}
and it is used like this…
它是这样使用的......
List<string> entities = new List<string>();
entities.Add("Value 1");
entities.Add("Value 2");
entities.Add("Value 3");
entities.Add("Value 4");
Collection<string> convertedEntities = entities.ToCollection<string>();
回答by Matthew M.
Why not just do the following:
为什么不做以下事情:
Collection<string> collection = new Collection<string>(theList);
as Collection(IList input) takes a List as part of construction.
作为 Collection(IList input) 将 List 作为构造的一部分。
回答by Shadi Namrouti
This is how you convert from List<T>
to Collection<T>
(while using LINQ):
这是您从 转换List<T>
为Collection<T>
(使用 LINQ 时)的方式:
The old function:
旧函数:
public List<Employee> GetEmployee(int id)
{
return ( from e in MyDataContext.Employees
select new Employee()
{
e.empId = id
}
).ToList();
}
After conversion:
转换后:
using System.Collection.ObjectModel;
public Collection<Employee> GetEmployee(int id)
{
return new Collection<Employee>(
(from e in MyDataContext.Employees
select new Employee()
{
e.empId = id
}
).ToList() as IList<Employee>
);
}
回答by Bala Subramaniam
You can use the the below
您可以使用以下
public class EmployeeCollection : Collection<Employee>
{
public EmployeeCollection(IList<Employee> list) : base(list)
{}
public EmployeeCollection() : base()
{}
}
Use the class like this
像这样使用这个类
EmployeeCollection employeeCollection = new EmployeeCollection(list)
回答by Alexis Gassan
The other way around, it is not necessary to loop... you can make just .ToList()
反过来,没有必要循环......你可以只做 .ToList()
ICollection<T> collection = new Collection<T>();
fill your collection using any method, and when you need the list, just do this:
使用任何方法填充您的集合,当您需要列表时,只需执行以下操作:
List<T> list = collection.ToList();
after that you can use whatever you want with your list.
之后,您可以在列表中使用任何您想要的内容。
Have a good coding!
有一个很好的编码!