我今天遇到了一个很奇怪的问题:
基本上,我想使用以下行将一种类型的数组转换为另一种类型的数组:
DirectoryInfo Source = new DirectoryInfo(@"C:\Orpheus_Music"); FileInfo[] Files = Source.GetFiles("*.mp3"); ListFileList = new List (); MusicFileModel temp = new MusicFileModel(); foreach (FileInfo file in Files) { temp.Name = file.Name.ToString(); temp.Pfad = file.DirectoryName.ToString(); FileList.Add(temp); Debug.WriteLine(temp.Name + ", " + temp.Pfad); } Debug.WriteLine("_______________"); foreach (MusicFileModel file in FileList) { Debug.WriteLine(file.Name + ", " + file.Pfad); }
但是,这不是获取Name和Pfad值的精确副本,而是输出:
01 Rolling in the Deep.mp3, C:\Orpheus_Music 02 Rumour has it.mp3, C:\Orpheus_Music 03 Turning Tables.mp3, C:\Orpheus_Music 04 Don't you remember.mp3, C:\Orpheus_Music 05 Set Fire to the Rain.mp3, C:\Orpheus_Music 06 He won't go.mp3, C:\Orpheus_Music 07 Take it all.mp3, C:\Orpheus_Music 08 I'll be waiting.mp3, C:\Orpheus_Music 09 One and only.mp3, C:\Orpheus_Music 10 Lovesong.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music _______________ 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music 11 Someone like you.mp3, C:\Orpheus_Music
这里出了什么问题?坦率地说这似乎是一个初学者的问题,但是,我无法找出究竟是什么导致了这一问题.
谢谢您的帮助!迈克尔赫伯特
你每次都在循环中更新同一个对象,所以你最终得到了你的对象的相同副本,List
最后它只包含在最后一次迭代中设置的值,你必须在循环中实例化新对象然后将其添加到List
:
foreach (FileInfo file in Files) { MusicFileModel temp = new MusicFileModel(); // note this temp.Name = file.Name.ToString(); temp.Pfad = file.DirectoryName.ToString(); FileList.Add(temp); Debug.WriteLine(temp.Name + ", " + temp.Pfad); }
你也可以使用Linq Select()
使它更简单,但它需要更多的操作,所以对于性能来说,每个循环的简单性更好,但你也可以通过以下方式实现:
FileList = Source.GetFiles("*.mp3") .Select(file => new MusicFileModel() { Name = file.Name.ToString(), Pfad = file.DirectoryName.ToString() }).ToList();