我正在尝试打印堆栈的内容。
堆栈类
当我尝试时,我会得到以下错误。
未处理的异常。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并尝试访问null的.Current
属性,从而获得一个NullReferenceExcpetion
。
要解决此问题,可以使用以下实现:
public IEnumerator GetEnumerator()
{
while (list.Any())
yield return Pop();
}