【发布时间】:2017-04-06 15:57:43
【问题描述】:
我在尝试填充字符串列表时遇到问题。 (每个列表代表一个要打印的页面,列表中的每个字符串都是页面上的一行文本)。字符串列表列表表示文档的整个文本。我需要这个List<List<string>>,这样我就可以将每个文档与其各自的配置文件配对。
我将相关代码复制到这里:
这是我的变量以及我用于 List<List<string>> 的访问器和修改器
private static readonly TemplateSingleton instance = new TemplateSingleton();
private List<string> lineOfPage;
private List<List<string>> _streamList;
public List<List<string>> StreamList
{
get { return _streamList; }
set { value = _streamList; }
}
这是破坏的方法:
#region Generate Lists
//Takes the stream of data and adds it to a list that can be processed.
public void GenerateLists(ref List<List<string>> arg, ReportConfig cfg)
{
if (TemplateSingleton.Instance.CurrentReportNum == 0)
{
TemplateSingleton.Instance.CFGList = new List<ReportConfig>();
TemplateSingleton.Instance.ReportsList = new List<Templates>();
}
TemplateSingleton.Instance.CFGList.Add(cfg);
TemplateSingleton.Instance.ReportsList.Add(TemplateSingleton.Instance.ChooseTemplate(cfg));
if (StreamList == null)
{
//Create a list of array values to hold them.
StreamList = new List<List<string>>(arg.Count);
}
int counter = 0;
foreach (List<string> argString in arg)
{
//Build a new array with the size equal to the number of lines.
lineOfPage = new List<string>();
//If the string isn't null...
if (argString != null)
{
//for each line of each page...
foreach (string str in argString)
{
//...If *that* string isn't null...
if (str != null)
{
//...add the string to the array of lines on a page.
lineOfPage.Add(str);
}
}
//list.Add(lineOfPage);
//A lot to unpack here. Add each line of a page, where the line of a page isn't empty, as an array, then convert the result back to a list.
StreamList.Add(new List<string>(lineOfPage.ToArray().Where(x => !string.IsNullOrEmpty(x)).ToList()));
}
//Add the list to my List of Lists
TemplateSingleton.Instance.ListOfStringLists.Add(StreamList);
}
当我运行代码时,我的其他列表初始化得很好。但是当它尝试做时
StreamList.Add(new List<string>(lineOfPage.ToArray().Where(x => !string.IsNullOrEmpty(x)).ToList()));
它坏了。它也不是我使用的 LINQ。当我运行它时
StreamList.Add(argString);
我得到同样的错误。我尝试了很多不同的东西。错误的确切位置(我可以看到)是当初始化我的 StreamList (StreamList = new List>()) 的行执行时,它实际上并没有初始化。事实上,它仍然显示为 null 值(当我逐步执行该方法时)。
我现在只写了几个月的代码。我学到了很多很酷的东西,但是我使用的一些关于 vars 的属性(比如 List)可能有我不熟悉的限制。我很感激你们能提供的任何帮助。谢谢!
编辑:这个问题已经得到解答。这是一个愚蠢的错字,打破了它。如果有人遇到同样的问题,我会发布有效的更新代码。
private static readonly TemplateSingleton instance = new TemplateSingleton();
private List<string> lineOfPage;
private List<List<string>> _streamList;
public List<List<string>> StreamList
{
get { return _streamList; }
set { _streamList = value; }
}
或者
public List<List<string>> StreamList { get; set; } //Automatically implemented property.
感谢您的帮助!
【问题讨论】:
-
看看你的二传手:
set { value = _streamList; }。那是坏了。现在是了解自动实现属性的好时机... -
@Jon Skeet 是吗?应该怎么设置?
-
好吧,您应该拥有
set { _streamList = value; }而不是将现有值复制到属性参数中......但使用public List<List<string>> StreamList { get; set; }会更简单 -
@JonSkeet 哦!我要试一试。 brb。
-
arg也不需要在您向我们展示的代码中使用ref修饰符...
标签: c# linq list object singleton