Does anyone want a framework/class which allows me to clone by values .Net objects? I\'m only interested with public read/write properties (namely DataContracts), and I don\
Try AutoMapper or BLToolkit Mapping
Dynamic Method based serialization will be fastest. (Generate a dynamic method using light weight codegen and use it for serialization)
You can do 1 method per property/field or one method for the whole object. From my benchmarking doing 1 per property does not give you too much of a performance hit.
See the following code, to see how I do this in Media Browser: http://code.google.com/p/videobrowser/source/browse/trunk/MediaBrowser/Library/Persistance/Serializer.cs
There are also some unit tests there.
There is fast reflection sample on theinstructionlimit that does exactly what you want.
see:
http://theinstructionlimit.com/?p=76
The CGbR Code Generator can generate an implementation of ICloneable for you. All you need is the nuget package and a partial class definition that implements ICloneable
. The generator will do the rest for you:
public partial class Root : ICloneable
{
public Root(int number)
{
_number = number;
}
private int _number;
public Partial[] Partials { get; set; }
public IList<ulong> Numbers { get; set; }
public object Clone()
{
return Clone(true);
}
private Root()
{
}
}
public partial class Root
{
public Root Clone(bool deep)
{
var copy = new Root();
// All value types can be simply copied
copy._number = _number;
if (deep)
{
// In a deep clone the references are cloned
var tempPartials = new Partial[Partials.Length];
for (var i = 0; i < Partials.Length; i++)
{
var value = Partials[i];
value = value.Clone(true);
tempPartials[i] = value;
}
copy.Partials = tempPartials;
var tempNumbers = new List<ulong>(Numbers.Count);
for (var i = 0; i < Numbers.Count; i++)
{
var value = Numbers[i];
tempNumbers[i] = value;
}
copy.Numbers = tempNumbers;
}
else
{
// In a shallow clone only references are copied
copy.Partials = Partials;
copy.Numbers = Numbers;
}
return copy;
}
}