1 | using System;
|
---|
2 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; |
---|
3 | |
---|
4 | namespace HeuristicLab.Problems.ProgramSynthesis {
|
---|
5 | [Serializable]
|
---|
6 | [StorableClass]
|
---|
7 | public abstract class StatefulExpression<T> : Expression, IPooledObject {
|
---|
8 | [Storable]
|
---|
9 | public T State { get; protected set; }
|
---|
10 | [NonSerialized]
|
---|
11 | private int? hashCode;
|
---|
12 | [NonSerialized]
|
---|
13 | private string stringRepresentation;
|
---|
14 |
|
---|
15 | protected StatefulExpression(T state) {
|
---|
16 | State = state;
|
---|
17 | }
|
---|
18 |
|
---|
19 | [StorableConstructor]
|
---|
20 | protected StatefulExpression(bool deserializing) : base(deserializing) { }
|
---|
21 |
|
---|
22 | protected virtual int CalcHashCode() {
|
---|
23 | var hash = 19 * 31 + GetType().FullName.GetHashCode();
|
---|
24 | hash = hash * 31 + State.GetHashCode();
|
---|
25 |
|
---|
26 | return hash;
|
---|
27 | }
|
---|
28 |
|
---|
29 | protected virtual string GetStringRepresentation() {
|
---|
30 | return State.ToString();
|
---|
31 | }
|
---|
32 |
|
---|
33 | public override string StringRepresentation {
|
---|
34 | get {
|
---|
35 | return stringRepresentation ?? (stringRepresentation = GetStringRepresentation());
|
---|
36 | }
|
---|
37 | }
|
---|
38 |
|
---|
39 | public override bool Equals(object obj) {
|
---|
40 | if (ReferenceEquals(this, obj))
|
---|
41 | return true;
|
---|
42 |
|
---|
43 | if (GetType() != obj.GetType())
|
---|
44 | return false;
|
---|
45 |
|
---|
46 | var other = (StatefulExpression<T>)obj;
|
---|
47 |
|
---|
48 | return ReferenceEquals(State, other.State) ||
|
---|
49 | GetHashCode() == other.GetHashCode();
|
---|
50 | }
|
---|
51 |
|
---|
52 | public bool Equals(StatefulExpression<T> obj) {
|
---|
53 | if (ReferenceEquals(this, obj))
|
---|
54 | return true;
|
---|
55 |
|
---|
56 | if (GetType() != obj.GetType())
|
---|
57 | return false;
|
---|
58 |
|
---|
59 | return ReferenceEquals(State, obj.State) ||
|
---|
60 | GetHashCode() == obj.GetHashCode();
|
---|
61 | }
|
---|
62 |
|
---|
63 | public override int GetHashCode() {
|
---|
64 | if (hashCode == null) hashCode = CalcHashCode();
|
---|
65 | return hashCode.Value;
|
---|
66 | }
|
---|
67 |
|
---|
68 | public void Reset() {
|
---|
69 | State = default(T);
|
---|
70 | }
|
---|
71 | }
|
---|
72 | } |
---|