This repository has been archived by the owner on Nov 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
/
ClonableClass.cs
92 lines (79 loc) · 1.89 KB
/
ClonableClass.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using NUnit.Framework;
namespace Logos.Utility.Tests
{
/// <summary>
/// Provides a reference implementation of a clonable class.
/// </summary>
/// <remarks>See <a href="http://code.logos.com/blog/2008/06/implementing_clone.html">Implementing Clone</a>.</remarks>
public class ClonableBase
{
public ClonableBase()
{
}
public int Count { get; set; }
public ClonableBase Clone()
{
return CloneCore();
}
protected virtual ClonableBase CloneCore()
{
return new ClonableBase(this);
}
protected ClonableBase(ClonableBase other)
{
Count = other.Count;
}
}
public class ClonableDerived : ClonableBase
{
public ClonableDerived()
{
}
public string Name { get; set; }
public new ClonableDerived Clone()
{
return (ClonableDerived) CloneCore();
}
protected override ClonableBase CloneCore()
{
return new ClonableDerived(this);
}
protected ClonableDerived(ClonableDerived other)
: base(other)
{
Name = other.Name;
}
}
[TestFixture]
public class ClonableClassTests
{
[Test]
public void CloneBase()
{
ClonableBase b = new ClonableBase { Count = 3 };
ClonableBase b2 = b.Clone();
Assert.That(b2, Is.Not.SameAs(b));
Assert.That(b2.Count, Is.EqualTo(b.Count));
}
[Test]
public void CloneDerived()
{
ClonableDerived d = new ClonableDerived { Count = 3, Name = "Test" };
ClonableDerived d2 = d.Clone();
Assert.That(d2, Is.Not.SameAs(d));
Assert.That(d2.Count, Is.EqualTo(d.Count));
Assert.That(d2.Name, Is.EqualTo(d.Name));
}
[Test]
public void CloneDerivedAsBase()
{
ClonableBase b = new ClonableDerived { Count = 3, Name = "Test" };
ClonableBase b2 = b.Clone();
Assert.That(b2, Is.Not.SameAs(b));
Assert.That(b2.Count, Is.EqualTo(b.Count));
Assert.That(b2, Is.TypeOf<ClonableDerived>());
Assert.That(((ClonableDerived) b2).Name, Is.EqualTo(((ClonableDerived) b).Name));
}
}
}