简体   繁体   中英

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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