gpt4 book ai didi

C# 引用参数传递

转载 作者:行者123 更新时间:2023-11-30 15:49:21 24 4
gpt4 key购买 nike

我有一段代码不工作,我很感激你们能给我的任何帮助

下面的代码正在生成一个异常......但我认为它不应该,除非我误解了 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();
}
}
}

最佳答案

问题是在函数 Produce 中你正在实例化一个新的 Queue并将其分配给私有(private)成员 One._queue ;这会覆盖您对 One._queue 所做的分配在构造函数中。但是,本地_queue指不同的 Queue<string>你从未排队。

您可以通过删除第一行 Produce 来解决此问题获得以下内容:

public void Produce() {
_queue.Enqueue("one");
}

顺便说一句,你不需要传递 _queue通过引用到构造函数中来实现你想要实现的目标。也就是说,以下也将起作用

public One(Queue<string> queue) {
_queue = queue;
}

当您需要本地 _queue 时,将使用引用传递在 main 中引用 Queue<string> 的不同实例在One之后构造函数执行。

关于C# 引用参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1671352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com