繁体   English   中英

如何实现 IEnumerable<T> 界面?

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

我从教科书中获取了这段代码,但它无法编译,我完全被卡住了。

我觉得如果您是一位经验丰富的 C# 用户,您将立即知道解决方案。 请您快速看一下。 这是游乐场的链接

错误

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'

代码

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>派生自IEnumerable (非泛型)。 所以如果你想实现第一个,你还必须实现第二个的成员。

因此,也必须实现IEnumerable.GetEnumerator() - 正如编译器提示的那样。

但是,这不起作用:

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

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

因为从编译器的角度来看,方法名(和参数)已经存在。 重载解析不考虑方法的返回类型。

解决方案是使用显式接口实现来实现“模糊”方法

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