开发者

How to create deferenced copy of an object in C#?

开发者 https://www.devze.com 2023-02-12 08:59 出处:网络
I have an entity which I use to bind data with my WPF UI. I am in need to create a copy of the entity which I can use as \"original\" data anytime.

I have an entity which I use to bind data with my WPF UI. I am in need to create a copy of the entity which I can use as "original" data anytime.

Just creating new object and then assigning also carries references with it. So I need a copy of ent开发者_JAVA技巧ity object which has no effect of changes made on its source.

My entity contains value type properties and several nested collections.

Any suggestions/ideas on this?


You will need to write your own copy constructor: This shows how. http://msdn.microsoft.com/en-us/library/ms173116(v=vs.80).aspx

For collections you will need to copy the data too. Array.Copy will work for most for A hashtable you might need to go as far as Serialization or simply recreating the table.

SomeType[] myArray = new SomeType[orig.Count+ 1];

orig.CopyTo(myArray, 0);


Deep Copy in C#


Use this project: https://github.com/havard/copyable

0

精彩评论

暂无评论...
验证码 换一张
取 消