Skip to main content
 首页 » 编程设计

c#之防止字典中的对象修改

2024年02月13日15Free-Thinker

我正在使用以下 C# 代码:

DataTable table = GetDataTable(); 
Dictionary<int, DataTable> d = new Dictionary<int, DataTable>(); 
d.Add(1, table); 
table = modifyTable(table); 
 
//Do some operations on d[1] 

这里,当我更改表格时,dictionary(d[1]) 中的表格正在更改。如何防止修改字典中的表格?为什么会出现这种行为?

请您参考如下方法:

How can I prevent modification of table in Dictionary?

传递您的 DataTable 的副本。使用 DataTable.Copy 很容易创建方法:

DataTable table = GetDataTable(); 
Dictionary<int, DataTable> d = new Dictionary<int, DataTable>(); 
d.Add(1, table.Copy()); 

Why is this behavior?

您正在传递对 DataTable 的引用,因为 DataTable 是引用类型。因此,您有两个引用指向一个 DataTable 实例。因此,当您使用 d[1] 返回的引用进行操作时,您正在修改由 table 引用引用的同一对象。