我如何将队列的值(不参考(插入另一个队列?它就像我在C (Queue<*Word>(中的点队一样工作,但是我想像这样复制缓冲区队列的值
a = 1;
int[] array = new int[1]
array[0] = a //array[0] now is 1
a = 0 // but array[0] doesn't change, array[0] is 1!
我有问题。
using word = System.Collections.Generic.Queue<char>;
Queue<word> words = new Queue<word>(); //word is the custom type, that was def in file top
word buffer = new word();
for (var symbol_count = 0; symbol_count < text.Length; ++symbol_count)
{
if (text[symbol_count] != ' ' && text[symbol_count] != '.' && text[symbol_count] != ',')
{
buffer.Enqueue(text[symbol_count]); //store one char in word
}
else
{
buffer.Enqueue(text[symbol_count]); //store end of word symbol
words.Enqueue(buffer); //store one word in words queue, but compiler do it like I try to copy a reference of buffer, not it value!!!
//System.Console.WriteLine(words.Count); DEBUG
buffer.Clear(); //clear buffer and when i do this, value in words queue is deleted too!!!
}
}
问题是您在循环中重复使用相同的buffer
,因此,当您清除它时,所有对其的参考也将被清除。
相反,将本地buffer
变量设置为对象的a new 实例,以使其任何更改都不会影响我们刚刚存储的参考:
foreach (char chr in text)
{
buffer.Enqueue(chr);
if (chr == ' ' || chr == '.' || chr == ',')
{
words.Enqueue(buffer);
// reassign our local variable so we don't affect the others
buffer = new Queue<char>();
}
}
当您将新单词保存到队列时(顺便说一句,您可能有一个错误的错误(
(words.Enqueue(buffer);
您不应该使用buffer
变量本身:它具有对临时数据的引用,您需要先制作它的副本,这将在下一行中不会修改。
尝试,例如
words.Enqueue(new word(buffer));