在尝试实现IEnumerable时为数组实现wrap类时出现问题

dev*_*ium 2 c# arrays ienumerable

我正在实现一个基本包装数组的类:

public abstract class IndividualBase : IEnumerable<Gene>
{
    private readonly Gene[] genoma;

    ...

    public IEnumerator<Gene> GetEnumerator()
    {
        return genoma.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return genoma.GetEnumerator();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,它给我带来了第一个问题GetEnumerator()- 它告诉我

无法将类型'System.Collections.IEnumerator'隐式转换为'System.Collections.Generic.IEnumerator'.存在显式转换(您是否错过了演员?)

虽然我明白问题是什么,但我完全不知道如何修复它.任何人?

谢谢

Mar*_*ell 7

你可以尝试:

IEnumerable<Gene> typed = genoma;
return typed.GetEnumerator();
Run Code Online (Sandbox Code Playgroud)

只是为了让编译器开心.当数组实现通用的Enumerable接口时,公共GetEnumerator()上不会出现这种情况.通过上面我们简单地转换为首选API.这是一个微不足道的演员; 在运行时不应该进行检查(因为编译器和CLI知道它是有效的).