2016-02-26 125 views
1

我想创建一个新的对象列表,我正在为我正在编写的程序运行时创建。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; 
     } 
    } 

然后包装它的代码仅仅是设置变量的方法。

+4

你有太多的评论你的代码是不可读的。 –

+0

pouplateModule是做什么的? – gh9

+0

定义了'noteFile'的位置?你还说你多次调用'ImportAllModules'?如果是这样,你是否也可以显示该代码。 – juharr

回答

0

没有理由说你的循环应该覆盖文件。你的代码看起来应该可以工作。

作为一个测试,你可以尝试像以下,而不是循环:

moduleList.AddRange(files.Select(x=>{ Module newModule = new Module(); newModule.PopulateModule(x); return newModule; });

并告诉我,然后会发生什么?

编辑:对于未来的访问者,问题是Module类的属性是静态的。这就是为什么每次迭代都会覆盖这些值。

+0

与该代码完全相同的事情发生。 – aljowen

+0

当你说“foreach循环的每次迭代”时,你是指循环的每次迭代还是循环所在函数的每次迭代?如果是后者,你是否在每次迭代中创建一个新用户? – Dabloons

+0

ImportAllModules只被调用一次。 foreach循环针对已打开的每个文件运行。 当我通过将出现以下情况的代码步骤: 第一次迭代: foreach循环与所述第一文件转换为一个对象正确地结束。 第二次迭代: [newModule line of code]检查新模块时,它仍然具有与先前迭代中的前一个模块相同的信息。 [填充行]新模块已正确填充,但列表中的所有其他模块现在都填充了相同的数据。 [add to list line]将新模块添加到列表中。 – aljowen