我想创建一个新的对象列表,我正在为我正在编写的程序运行时创建。C#列表覆盖
public class User //This is a datastructure to hold all modules as well as any other user data
{
List<Module> moduleList = new List<Module>(); //list to contain all modules
public void ImportAllModules() //Imports all files within the module file folder
{
List<List<string>> files = noteFile.getAllFiles(noteFile.moduleLoc); //Creates a jagged List of all files and contents within each file
foreach (List<string> file in files) //For every file it creates a newmodule object
{
Module newModule = new Module(); //Creates new object
newModule.PopulateModule(file); //Fully populates the object from the file
moduleList.Add(newModule); //Adds the new module object onto the list of modules
}
}
}
我发现每次迭代foreach循环都会覆盖列表中的所有以前的项目。例如,如果我试图添加6个对象,则每个对象都将被添加,但随后将被下一个循环中的下一个对象覆盖。
程序(此时)正在将文件夹中的每个文件加载到2d锯齿形列表中,以便将x轴上的每个文件以及y轴上的每行文本(每个文件内)都显示为可视化文件。然后我正在运行一个foreach循环,从那些使用2d锯齿阵列的文件中提取有用的数据,并将它们转换为可在我的程序中使用的对象。我将它们存储在一个列表中,以便于组织新对象。
我曾尝试寻找解决方案,但其他人的问题是,他们宣布的对象之外的循环,我不这样做。
感谢您的帮助:)
编辑: 这里是填入模块方法
public void PopulateModule(List<string> file) //This will do all of the imports from a single file in one handy method
{
Code(ImpCode(file));
Title(ImpTitle(file));
Synopsis(ImpSynopsis(file));
LearnObj(ImpLO(file));
Assignments(ImpAssignment(file));
Notes(ImpNote(file));
}
。不过我想这是不适合你自身的那么有用,所以这里的东西它实际上做的ImpCode:
public string ImpCode(List<string> file) //importing learning module code
{
try
{
return file[file.IndexOf("CODE") + 1];//looks for the section heading in the file, then gets the next line of the file which will have the contents and returns it.
}
catch (Exception ex)
{
MessageBox.Show(Convert.ToString(ex), "Error"); //Displays the generated error message to the user
return null;
}
}
然后包装它的代码仅仅是设置变量的方法。
你有太多的评论你的代码是不可读的。 –
pouplateModule是做什么的? – gh9
定义了'noteFile'的位置?你还说你多次调用'ImportAllModules'?如果是这样,你是否也可以显示该代码。 – juharr