我有一段代码不起作用,我会很感激你们可以为我提供的任何帮助
下面的代码正在生成一个异常......但我认为它不应该,除非我误解了 ref 语义。
编辑:感谢所有的回答......我知道我在 One.Produce 方法中创建了一个新的 Queue 对象......但这是我真正想要做的,我希望 Main._queue 持有参考到 One._queue。这有可能吗?
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class One
{
Queue<string> _queue;
public One(ref Queue<string> queue)
{
// should be assigning by reference
_queue = queue;
}
public void Produce()
{
_queue = new Queue<string>();
_queue.Enqueue("one");
}
}
class Program
{
static void Main(string[] args)
{
Queue<string> _queue = new Queue<string>();
One one = new One(ref _queue);
one.Produce();
// this generates an exception, since _queue is empty
// i'd have thought _queue would have one item, "one"
string value = _queue.Dequeue();
}
}
}