using System; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; namespace HeuristicLab.Problems.ProgramSynthesis { [Serializable] [StorableClass] public abstract class StatefulExpression : Expression, IPooledObject { [Storable] public T State { get; protected set; } [NonSerialized] private int? hashCode; [NonSerialized] private string stringRepresentation; protected StatefulExpression(T state) { State = state; } [StorableConstructor] protected StatefulExpression(bool deserializing) : base(deserializing) { } protected virtual int CalcHashCode() { var hash = 19 * 31 + GetType().FullName.GetHashCode(); hash = hash * 31 + State.GetHashCode(); return hash; } protected virtual string GetStringRepresentation() { return State.ToString(); } public override string StringRepresentation { get { return stringRepresentation ?? (stringRepresentation = GetStringRepresentation()); } } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (GetType() != obj.GetType()) return false; var other = (StatefulExpression)obj; return ReferenceEquals(State, other.State) || GetHashCode() == other.GetHashCode(); } public bool Equals(StatefulExpression obj) { if (ReferenceEquals(this, obj)) return true; if (GetType() != obj.GetType()) return false; return ReferenceEquals(State, obj.State) || GetHashCode() == obj.GetHashCode(); } public override int GetHashCode() { if (hashCode == null) hashCode = CalcHashCode(); return hashCode.Value; } public void Reset() { State = default(T); } } }