列表通用GetEnumerator转换为接口失败

时间:2013-04-20 22:19:41

标签: c# .net interface enumerator

GetEnumerator强制转换为接口失败
没有编译器错误
消息索引无穷大的运行时故障
如果我直接使用结构Word1252没有接口它可以工作

namespace WordEnumerable
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            WordEnum wordEnum = new WordEnum();
            Debug.WriteLine(wordEnum[0].GetType().ToString());
            Debug.WriteLine(wordEnum[0].Value);
            Debug.WriteLine(wordEnum.Count.ToString());
            foreach (iWord w in wordEnum)  // fails here
            {
            }
        }
    }
}
public interface iWord
{
    Int32 Key { get; }
    String Value { get; }
}
public class WordEnum : IEnumerable<iWord>
{
    private static List<Word1252> words1252 = new List<Word1252>();
    IEnumerator<iWord> IEnumerable<iWord>.GetEnumerator()
    {
        return ((IEnumerable<iWord>)words1252).GetEnumerator();
    }
    public struct Word1252 : iWord
    {
        public UInt64 packed;
        public Int32 Key   { get { return (Int32)((packed >> 27) & ((1 << 25) - 1)); } }
        public Byte Length { get { return (Byte) ((packed >> 59) & ((1 <<  5) - 1)); } }
        public String Value { get { return Key.ToString(); } }
        public Word1252(UInt64 Packed) { packed = Packed; }
    }

1 个答案:

答案 0 :(得分:1)

简而言之upcastingIEnumerable<Word1252>IEnumerable<IWord>

这需要covariance才能运作。

  

即使IEnumerable被标记为out(协变)
  协方差不适用于&#39;值类型&#39; - 即您拥有的结构   界面定义。

e.g。见......

Is this a covariance bug in C# 4?
(或者有点不同,但归结为相同的问题)
Why cannot IEnumerable<struct> be cast as IEnumerable<object>?

要解决此问题,您只需定义列表

即可
private static List<iWord> words1252 = new List<iWord>();  

或者像这样定义你的枚举器:

IEnumerator<iWord> IEnumerable<iWord>.GetEnumerator()
{
    foreach (var word in words1252)
        yield return word;
}