我正在尝试打印堆栈的内容。
当我尝试时,出现以下错误。
未处理的异常。 System.NullReferenceException:对象引用未设置为对象的实例。
这发生在我代码的foreach行上。我不确定为什么会这样,因为我以为我使用的是链接页面上给出的示例。例子是...
foreach( string number in numbers )
{
Console.WriteLine(number);
}
以下是我的代码。除了该部分会引发错误之外,其他所有东西似乎都正常工作。
foreach(var s in stack)
{
Console.WriteLine(s);
}
...这是我的代码。
using System;
namespace Exercise
{
class Program
{
static void Main()
{
var stack = new Stack();
stack.Push(1);
stack.Push(2);
stack.Push(3);
foreach(var s in stack)
{
Console.WriteLine(s);
}
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Exercise
{
internal class Stack : IEnumerable
{
private object _object;
private List<object> list = new List<object>();
private IEnumerator Enumerator;
public IEnumerator GetEnumerator() => Enumerator;
internal object Pop()
{
if (list.Count == 0)
throw new InvalidOperationException("Cannot use .Pop() if list count equals 0.");
_object = list.FirstOrDefault();
list.RemoveAt(0);
return _object;
}
internal void Push(object obj)
{
_object = obj;
if (_object == null)
throw new InvalidOperationException("Cannot use .Push() if object is null.");
list.Insert(0, _object);
}
internal void Clear()
{
if (list.Count == 0)
throw new InvalidOperationException("Cannot use .Clear() if list is empty.");
list.Clear();
}
}
}
我在做什么错,如何解决这个问题以打印堆栈中的内容?
您的GetEnumerator
方法返回null,因为从未显式初始化字段Enumerator
,因此它的默认值为null。
然后,foreach循环调用.GetEnumerator()
,接收到空值并尝试访问null的.Current
属性,因此您得到了NullReferenceExcpetion
。
要解决此问题,您可以使用以下实现:
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return Pop();
}