创建列表的副本

zuh*_*h4n 3 .net c# winforms

我需要存储两个变量,然后检查它们是否没有改变.

List<CatalogInfo> list_catalogs = new List<CatalogInfo>();
List<FileInfo> list_files = new List<FileInfo>(); 
List<CatalogInfo> list_catalogs_for_check_changed = new List<CatalogInfo>();
List<FileInfo> list_files_check_changed = new List<FileInfo>();
Run Code Online (Sandbox Code Playgroud)

当我做:

list_catalogs_for_check_changed = list_catalogs;
list_files_check_changed = list_files;
Run Code Online (Sandbox Code Playgroud)

但是当我添加到list_catalogs或list_files项目时,我在debager中看到Items添加到list_catalogs_for_check_changed或list_files_check_changed.为什么???我没有用变量添加项目.

  list_catalogs.Add(new CatalogInfo() { Action = "Create", Path = folderBrowserDialog1.SelectedPath });
Run Code Online (Sandbox Code Playgroud)

Ant*_*t P 6

当你这样做:

list_catalogs_for_check_changed = list_catalogs;
Run Code Online (Sandbox Code Playgroud)

您没有复制列表,而是为同一列表分配新引用.如果要创建包含相同项目的新列表,请执行以下操作:

    list_catalogs_for_check_changed = new List<CatalogInfo>(list_catalogs);
Run Code Online (Sandbox Code Playgroud)

这将分配一个新的List<CatalogInfo>并传递要从中复制元素的列表,从而生成两个具有相同项目的独立列表.