source: branches/HeuristicLab.Problems.BioBoost/HeuristicLab.Problems.BioBoost/3.3/Utils/Closure.cs @ 13069

Last change on this file since 13069 was 13069, checked in by gkronber, 7 years ago

#2499: imported source code for HeuristicLab.BioBoost from private repository with some changes

File size: 1.8 KB
Line 
1using HeuristicLab.Common;
2using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
3using System;
4
5namespace HeuristicLab.BioBoost.Utils {
6
7  /// <summary>
8  /// Wraps a field into a local variable inside the constructor. This evades
9  /// object graph traversal as the actual value is no longer discoverable by
10  /// reflection. Use with Caution!
11  /// </summary>
12  /// <typeparam name="T">The Type of the value to be wrapped.</typeparam>
13  [StorableClass]
14  public class Closure<T> : IDeepCloneable {
15
16    public enum Encapsulation { Cloned, Referenced };
17
18    [Storable]
19    private readonly Encapsulation encapsulation;
20
21    [Storable]
22    public T Value { get { return Getter(); } set { Setter(value); } }
23
24    public Func<T> Getter;
25    public Action<T> Setter;
26
27    [StorableConstructor]
28    protected Closure(bool isDeserializing) {
29      T value = default(T);
30      Getter = () => value;
31      Setter = v => value = v;
32    }
33    protected Closure(Closure<T> orig, Cloner cloner) {
34      T value = default(T);
35      Getter = () => value;
36      Setter = v => value = v;
37      encapsulation = orig.encapsulation;
38      cloner.RegisterClonedObject(orig, this);
39      if (encapsulation == Encapsulation.Referenced) {
40        Value = orig.Value;
41      } else {
42        var cloneable = orig.Value as IDeepCloneable;
43        if (cloneable != null)
44          Value = (T) cloner.Clone(cloneable);
45        else
46          Value = orig.Value;
47      }
48    }
49    public Closure(Encapsulation encapsulation) {
50      this.encapsulation = encapsulation;
51      T value = default(T);
52      Getter = () => value;
53      Setter = v => value = v;
54    }
55
56    public object Clone() {
57      return Clone(new Cloner());
58    }
59
60    public IDeepCloneable Clone(Cloner cloner) {
61      return new Closure<T>(this, cloner);
62    }
63  }
64}
Note: See TracBrowser for help on using the repository browser.