不能隐式转换列表< T>以收集和LT; T> [英] Cannot implicitly convert List<T> to Collection<T>

查看:242
本文介绍了不能隐式转换列表< T>以收集和LT; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个编译器错误(稍微改变了可读性)。

This is a compiler error (slightly changed for readability).

本人们总是困惑我。的FxCop告诉这是一件坏事返回列表以及\\从派生类集合< T> 应该是preferrable的返回类型

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的说,这是确定使用列表&LT; T&GT; 的内部数据存储\\操作。
好吧,我得到它,但我不明白的是,编译器抱怨试图隐式转换列表&LT; T&GT; 收藏&LT; T&GT; 。是不是列表&LT; T&GT; 更多的接口充电和功能?
为什么禁止的隐式转换?

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?

和另外一个问题,从上面的茎:是新的List&LT; INT&GT;(一些集合&LT; INT&GT;)构造昂贵

And another question that stems from above: is new List<int>(some collection<int>) constructor expensive?

感谢您,

瓦伦丁·瓦西里耶夫

推荐答案

列表&LT; T&GT; 不会从收集和LT得到; T&GT; - 确实如此,但是,实施的ICollection&LT; T&GT; 。这将是返回类型的一个更好的选择。

List<T> doesn't derive from Collection<T> - it does, however, implement ICollection<T>. That would be a better choice of return type.

对于新的List&LT; INT&GT;(一些集合&LT; INT&GT;)的问题 - 这一定程度上取决于收集是什么。如果它实现的ICollection&LT; T&GT; (在执行时),那么构造函数可以使用它的计数属性创建列表通过它迭代和添加每个项目前右初始容量。如果不执行的ICollection&LT; T&GT; 那么它只是等同于:

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:

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.

我不相信构造做任何事情狡猾的阵列,它可能可以 - 使用 Array.Copy 或什么,只是在很多拷贝在一去,而不是迭代虽然。 (同样,如果它是另一个列表&LT; T&GT; 它可以得到的支持数组和复制直接)

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.)

这篇关于不能隐式转换列表&LT; T&GT;以收集和LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆