2016-02-26 126 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