我想創建一個新的對象列表,我正在爲我正在編寫的程序運行時創建。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