我從教科書中獲取了這段代碼,但它無法編譯,我完全被卡住了。
我覺得如果您是一位經驗豐富的 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;
}
}
}
uj5u.com熱心網友回復:
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();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/472754.html
標籤:C#
上一篇:將列舉轉換為json物件
