简体   繁体   English

如何实现 IEnumerable<T> 界面?

[英]How to implement IEnumerable<T> interface?

I took this code from a textbook and it does not compile and I'm completely stuck.我从教科书中获取了这段代码,但它无法编译,我完全被卡住了。

I feel like if you're an experienced C# user you will know the solution right away.我觉得如果您是一位经验丰富的 C# 用户,您将立即知道解决方案。 Could you please take a quick look at it.请您快速看一下。 Here's a link to playground这是游乐场的链接

Error错误

CS0738: 'LinkedList<T>' does not implement interface member 'IEnumerable.GetEnumerator()'. 'LinkedList<T>.GetEnumerator()' cannot implement 'IEnumerable.GetEnumerator()' because it does not have the matching return type of 'IEnumerator'

Code代码

using System.Collections.Generic;
                    
#nullable enable

public record LinkedListNode<T>(T Value)
{   
    public LinkedListNode<T>? Next { get; internal set; }
    public LinkedListNode<T>? Prev { get; internal set; }
    public override string? ToString() => Value?.ToString();
}


public class LinkedList<T> : IEnumerable<T>
{
  public LinkedListNode<T>? First { get; private set; }
  public LinkedListNode<T>? Last { get; private set; }
  public LinkedListNode<T> AddLast(T node)
  {
    LinkedListNode<T> newNode = new(node);
    if (First is null || Last is null)
    {
      First = newNode;
      Last = First;
    }
    else
    {
      newNode.Prev = Last;
      Last.Next = newNode;
      Last = newNode;
    }
    return newNode;
  }
  public IEnumerator<T> GetEnumerator()
  {
    LinkedListNode<T>? current = First;
    while (current is not null)
    {
      yield return current.Value;
      current = current.Next;
    }
  }
}

IEnumerable<T> derives from IEnumerable (non generic). IEnumerable<T>派生自IEnumerable (非泛型)。 So if you want to implement the first, you also have to implement the members of the second.所以如果你想实现第一个,你还必须实现第二个的成员。

IEnumerable.GetEnumerator() must thus also be implemented - as the compiler hints.因此,也必须实现IEnumerable.GetEnumerator() - 正如编译器提示的那样。

However, this will not work:但是,这不起作用:

public class LinkedList<T> : IEnumerable<T>
{
    // ... existing code

    public System.Collections.IEnumerator GetEnumerator() { /* ... */ }
}

Because from the compiler's point of view method by that name (and parameters) already exists.因为从编译器的角度来看,方法名(和参数)已经存在。 Overload resolution does not consider the return type of the method. 重载解析不考虑方法的返回类型。

The solution is to implement the "ambigous" method using explicitl interface implementation解决方案是使用显式接口实现来实现“模糊”方法

public class LinkedList<T> : IEnumerable<T>
{
    // ... existing code

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM