当我向List>父列表的每一项都得到相同的值
本文关键字:List 一项 string 列表 | 更新日期: 2023-09-27 18:02:14
抱歉,如果这个问题的答案是显而易见的,我对c#和OOP相当陌生。我已经通过我的代码,花了相当多的时间在谷歌上,但我找不到我的问题的答案(很可能是因为我使用了错误的搜索条件!)。
我有下面的类,创建一个静态的List<List<string>>
,并有一个方法来添加项目到该列表:
public static class WordList
{
static List<List<string>> _WordList; // Static List instance
static WordList()
{
//
// Allocate the list.
//
_WordList = new List<List<string>>();
}
public static void Record(List<string> Words)
{
//
// Record this value in the list.
//
_WordList.Add(Words);
}
}
在其他地方,我创建了一个List<string>
,我传递给Record()
方法添加到_WordList
。问题是当我向WordList添加项目时,它会给该列表中的每个项目相同的值。例如:
添加的第一个项目包含"Foo"answers"bar"
添加的第二项包含"Not","Foo"answers"bar"
所以不是像这样的列表:
1: "Foo","bar"
2: "Not","Foo","bar"
我结束了:
1: "Not","Foo","bar"
2: "Not","Foo","bar"
我没有使用List<string[]>
而不是List<List<string>>
,因为我获得List<string>
添加的方式是通过逐行读取文本文件,用分隔符表示何时应该添加List<string>
并清除它,以便我可以重新开始。因此,我不知道我需要声明的数组有多长。
希望这是有意义的!如果你需要更多的代码发布来帮助,请告诉我。
谢谢,提前。
编辑
下面是创建传递给Record()
方法的List<string>
的代码。我想我看到人们在说什么不创建List<string>
的新实例,但我不知道如何补救这方面我的代码。我会考虑一下,如果我想出一个答案,我会贴出来的!
public static void LoadWordList(string path)
{
string line;
List<string> WordsToAdd = new List<string>();
StreamReader file = new System.IO.StreamReader(path);
while ((line = file.ReadLine()) != null)
{
if (line.Substring(0, 1) == "$")
{
WordList.Record(WordsToAdd);
WordsToAdd.Clear();
WordsToAdd.Add(line.Replace("$", ""));
}
else
{
WordsToAdd.Add(line.Replace("_"," "));
}
}
file.Close();
}
代替
WordList.Record(WordsToAdd);
WordsToAdd.Clear();
WordsToAdd.Add(line.Replace("$", ""));
WordList.Record(WordsToAdd);
WordsToAdd = new List<string>();
WordsToAdd.Add(line.Replace("$", ""));
您的Record
方法正在做的是添加对您传递给它的List<string>
的引用。然后清除相同的列表,并开始向其中添加不同的字符串。
可能是这样的:
public static void Record(IEnumerable<string> Words)
{
_WordList.Add(Words.ToList());
}
强制复制;此外,通过接受IEnumerable<string>
,它对调用它的代码施加了更少的限制。
你能发布添加列表的代码吗?我打赌你正在做类似
的事情。- 创建列表l
- 将它添加
- 修改l
- 将它添加
这将导致一个对象(因为您只创建了它一次)具有对它的多个引用,即来自_WordList中的第一个值,来自_WordList中的第二个值,来自l。
所以正确的做法是:
- 将它添加 创建新列表
- 将它添加
或者在代码中:
List<string> l = new string[] { "Foo", "bar" }.ToList();
WordList.Record(l);
l = new string[] { "Not", "Foo", "bar" }.ToList();
WordList.Record(l);
您还没有展示如何向列表中添加项。下面是一个正常工作的例子:
using System;
using System.Collections.Generic;
using System.Linq;
public static class WordList
{
static List<List<string>> _WordList; // Static List instance
static WordList()
{
_WordList = new List<List<string>>();
}
public static void Record(List<string> Words)
{
_WordList.Add(Words);
}
public static void Print()
{
foreach (var item in _WordList)
{
Console.WriteLine("-----");
Console.WriteLine(string.Join(",", item.ToArray()));
}
}
}
class Program
{
static void Main()
{
WordList.Record(new[] { "Foo", "bar" }.ToList());
WordList.Record(new[] { "Not", "Foo", "bar" }.ToList());
WordList.Print();
}
}