SoFunction
Updated on 2025-03-06

A brief analysis of C# replication and cloning

This article briefly analyzes the copy and cloning technology of C#, and friends in need can refer to it.

In C#, copy and clone using HashTable, DataTable, etc., let’s take a look at the examples directly:

HashTable ht = null;
ht = new HashTable();
foreach(string s in ht)
{
//...
}
//When traversing above, you need to modify the key value in the HashTable, and an exception will usually be reported, prompting that your collection has been modified XXX or something, because during foreach traversing, the collection behind in cannot be changed//At this time, I should have thought of it, and I should copy one before convenience.HashTable ht2 = new HashTable();
(ht2,0);

The above code can be debugged, but the problem comes again. After we modified the key value in ht2, we found that the key value in ht has also been modified. Obviously, this is not the result I want. Then we thought about it for a little bit and used Clone() to solve the problem.

DataTable Similarly, DataTable dt2 = () copy or directly give value is not possible, and it will also change the value in the original datatble.

Here you need to modify the key value in the HashTable, and an exception will generally be reported, prompting that your collection has been modified XXX or something, because during foreach traversal, the collection behind in cannot be changed.
At this time, I should have thought of it, and I should copy a copy before traversing.