In C#, if I have an IList
, and I do not know the type of the objects in the IList
, how can I create a copy of the IList
?
Here is the situation:
I have a CollectionEditor that can modify items in an IList
. If the cancel button is pressed, I need to restore the IList
before the items were changed.
There are two different problems here. Copying a list to another list is relatively easy - if you don't need the second list to be the exact same type of concrete list you could use ToList()
, otherwise you could just Add
in a loop. However, that won't solve your problem unless the T
here is something immutable. It would be fine for string
, int
etc, but copying the references to a complex type won't allow you to restore the list, as individual items could have been edited in the UI. To solve that problem you need a "deep copy" (or there are some other strategies, but that is the simplest). And as has been noted: one way to do a deep copy is: serialization. By taking a snapshot of the data in XML, json, or some other serialization format, "restore" can be implemented via "deserialize".
Of course, if your T
has a deep-clone method built in, you might be able to use that instead of serialization. It is ambiguous whether ICloneable
is deep vs shallow, so I don't think it is sufficient to insist where T : ICloneable
.
ToList创建一个副本:
IList x = y.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.