Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Parameters/3.3/LookupParameter.cs @ 4179

Last change on this file since 4179 was 3822, checked in by swagner, 15 years ago

Implemented reviewers' comments (#863)

  • adapted item names of generic items to reflect the type of their generic parameters
File size: 6.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
26
27namespace HeuristicLab.Parameters {
28  /// <summary>
29  /// A parameter whose value is retrieved from the scope.
30  /// </summary>
31  [Item("LookupParameter", "A parameter whose value is retrieved from or written to a scope.")]
32  [StorableClass]
33  public class LookupParameter<T> : Parameter, ILookupParameter<T> where T : class, IItem {
34    [Storable]
35    private string actualName;
36    public string ActualName {
37      get { return actualName; }
38      set {
39        if (value == null) throw new ArgumentNullException();
40        if (!actualName.Equals(value)) {
41          actualName = value;
42          OnActualNameChanged();
43        }
44      }
45    }
46    public string TranslatedName {
47      get {
48        string translatedName;
49        GetValueParameterAndTranslateName(out translatedName);
50        return translatedName;
51      }
52    }
53    public new T ActualValue {
54      get {
55        if (cachedActualValue == null) cachedActualValue = GetActualValue();
56        return (T)cachedActualValue;
57      }
58      set {
59        cachedActualValue = value;
60        SetActualValue(value);
61      }
62    }
63
64    public LookupParameter()
65      : base("Anonymous", typeof(T)) {
66      this.actualName = Name;
67    }
68    public LookupParameter(string name)
69      : base(name, typeof(T)) {
70      this.actualName = Name;
71    }
72    public LookupParameter(string name, string description)
73      : base(name, description, typeof(T)) {
74      this.actualName = Name;
75    }
76    public LookupParameter(string name, string description, string actualName)
77      : base(name, description, typeof(T)) {
78      this.actualName = actualName == null ? string.Empty : actualName;
79    }
80    [StorableConstructor]
81    protected LookupParameter(bool deserializing) : base(deserializing) { }
82
83    public override IDeepCloneable Clone(Cloner cloner) {
84      LookupParameter<T> clone = (LookupParameter<T>)base.Clone(cloner);
85      clone.actualName = actualName;
86      return clone;
87    }
88
89    public override string ToString() {
90      if (Name.Equals(ActualName))
91        return Name;
92      else
93        return Name + ": " + ActualName;
94    }
95
96    private IValueParameter GetValueParameterAndTranslateName(out string actualName) {
97      IValueParameter valueParam;
98      ILookupParameter lookupParam;
99      IExecutionContext currentExecutionContext = ExecutionContext;
100
101      actualName = Name;
102      while (currentExecutionContext != null) {
103        valueParam = currentExecutionContext.Parameters[actualName] as IValueParameter;
104        lookupParam = currentExecutionContext.Parameters[actualName] as ILookupParameter;
105
106        if ((valueParam == null) && (lookupParam == null))
107          throw new InvalidOperationException(
108            string.Format("Parameter look-up chain broken. Parameter \"{0}\" is not an \"{1}\" or an \"{2}\".",
109                          actualName, typeof(IValueParameter).GetPrettyName(), typeof(ILookupParameter).GetPrettyName())
110          );
111
112        if (valueParam != null) {
113          if (valueParam.Value != null) return valueParam;
114          else if (lookupParam == null) return valueParam;
115        }
116        if (lookupParam != null) actualName = lookupParam.ActualName;
117
118        currentExecutionContext = currentExecutionContext.Parent;
119        while ((currentExecutionContext != null) && !currentExecutionContext.Parameters.ContainsKey(actualName))
120          currentExecutionContext = currentExecutionContext.Parent;
121      }
122      return null;
123    }
124    private IVariable LookupVariable(string name) {
125      IScope scope = ExecutionContext.Scope;
126      while ((scope != null) && !scope.Variables.ContainsKey(name))
127        scope = scope.Parent;
128      return scope != null ? scope.Variables[name] : null;
129    }
130    protected override IItem GetActualValue() {
131      string name;
132      // try to get value from context stack
133      IValueParameter param = GetValueParameterAndTranslateName(out name);
134      if (param != null) return param.Value;
135
136      // try to get variable from scope
137      IVariable var = LookupVariable(name);
138      if (var != null) {
139        if (!(var.Value is T))
140          throw new InvalidOperationException(
141            string.Format("Type mismatch. Variable \"{0}\" does not contain a \"{1}\".",
142                          name,
143                          typeof(T).GetPrettyName())
144          );
145        return var.Value;
146      }
147      return null;
148    }
149    protected override void SetActualValue(IItem value) {
150      if (!(value is T))
151        throw new InvalidOperationException(
152          string.Format("Type mismatch. Value is not a \"{0}\".",
153                        typeof(T).GetPrettyName())
154        );
155      // try to set value in context stack
156      string name;
157      IValueParameter param = GetValueParameterAndTranslateName(out name);
158      if (param != null) {
159        param.Value = value;
160        return;
161      }
162
163      // try to set value in scope
164      IVariable var = LookupVariable(name);
165      if (var != null) {
166        var.Value = value;
167        return;
168      }
169
170      // create new variable
171      ExecutionContext.Scope.Variables.Add(new Variable(name, value));
172    }
173
174    public event EventHandler ActualNameChanged;
175    private void OnActualNameChanged() {
176      if (ActualNameChanged != null)
177        ActualNameChanged(this, EventArgs.Empty);
178      OnToStringChanged();
179    }
180  }
181}
Note: See TracBrowser for help on using the repository browser.