【发布时间】:2010-12-12 21:11:43
【问题描述】:
我有一段代码不工作,如果你们能提供任何帮助,我将不胜感激
下面的代码正在生成一个异常......但我认为它不应该,除非我误解了 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();
}
}
}
【问题讨论】:
-
它生成的异常会很有帮助...
-
为了响应您的编辑,您说您想在
One.Produce中实例化Queue<string>的新实例,但您希望Main中的本地_queue引用该对象也。在这种情况下,您需要将Produce的签名更改为Produce(ref Queue<string> queue)并添加queue = _queue = new Queue<string>()行,或者您需要让Produce返回对它创建并设置@ 的Queue<string>实例的引用987654331@Main. -
返回引用是最简单的,或者将 ref 更改为 out。
标签: c# parameters ref