c#-将T []强制转换为IList是否有任何警告?
作者:互联网
我正在实现一个包装项目数组的类,并且为了便于LINQ使用,我希望该类实现IEnumerable< T>.接口.
我第一次实现该类的“天真”尝试如下:
public class Foo<T> : IEnumerable<T>
{
private readonly T[] _items;
public Foo(T[] items) { _items = items; }
public IEnumerator<T> GetEnumerator() { return _items.GetEnumerator(); } // ERROR
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
但是,由于该阵列仅实现IEnumerable接口而不是IEnumerable< T> ;,因此将无法编译.编译错误为:
Cannot implicitly convert type ‘System.Collections.IEnumerator’ to ‘System.Collections.Generic.IEnumerator<T>’. An explicit conversion exists (are you missing a cast?)
为了克服此问题,我将数组局部转换为继承IEnumerable< T>的接口,例如IList< T> ;:
public IEnumerator<T> GetEnumerator() {
return ((IList<T>)_items).GetEnumerator();
}
这样可以成功编译,并且我的初步测试还表明该类可以正确地用作可枚举的集合.
但是,铸造方法并不完全令人满意.这种方法有什么需要注意的地方吗?能否以更可靠(类型安全)的方式解决问题?
解决方法:
似乎更好:
return ((IEnumerable<T>)_items).GetEnumerator();
arrays implement IEnumerable<T>
:
[…] this type implements
IEnumerable
andIEnumerable<T>
您的第一种方法行不通,因为IEnumerable.GetEnumerator和IEnumerable< T> .GetEnumerator之间存在歧义.
为什么在IDE中看不到它的问题解释为here:
Starting with the .NET Framework 2.0, the Array class implements the
System.Collections.Generic.IList<T>
,System.Collections.Generic.ICollection<T>
, andSystem.Collections.Generic.IEnumerable<T>
generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throwNotSupportedException
.
标签:ienumerable,casting,linq,arrays,c 来源: https://codeday.me/bug/20191122/2060777.html