Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 7501

Last change on this file since 7501 was 7467, checked in by mkommend, 13 years ago

#1760:

  • added possibility to exclude members from object graph traversal by name
  • excluded runs from object graph traversal in the Algorithm
  • adapted DeepCloneableCloningTest
File size: 4.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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 System.Collections;
24using System.Collections.Generic;
25using System.Collections.Specialized;
26using System.Linq;
27using System.Reflection;
28using System.Security;
29using System.Threading;
30
31namespace HeuristicLab.Common {
32  public static class ObjectExtensions {
33    public static IEnumerable<object> GetObjectGraphObjects(this object obj, HashSet<string> excludedMembers = null, bool excludeStaticMembers = false) {
34      if (obj == null) return Enumerable.Empty<object>();
35      if (excludedMembers == null) excludedMembers = new HashSet<string>();
36
37      var objects = new HashSet<object>();
38      var stack = new Stack<object>();
39
40      stack.Push(obj);
41      while (stack.Count > 0) {
42        object current = stack.Pop();
43        objects.Add(current);
44
45        foreach (object o in GetChildObjects(current, excludedMembers, excludeStaticMembers)) {
46          if (o != null && !objects.Contains(o) && !ExcludeType(o.GetType()))
47            stack.Push(o);
48        }
49      }
50
51      return objects;
52    }
53
54    /// <summary>
55    /// Types not collected:
56    ///   * System.Delegate
57    ///   * System.Reflection.Pointer
58    ///   * Primitives (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single)
59    ///   * string, decimal
60    ///   * Arrays of types not collected
61    ///   
62    /// Dictionaries and HashSets are treated specially, because it is cheaper to iterate over their keys and values
63    /// compared to traverse their internal data structures.
64    /// </summary>
65    private static bool ExcludeType(Type type) {
66      return type.IsPrimitive ||
67             type == typeof(string) ||
68             type == typeof(decimal) ||
69             typeof(Delegate).IsAssignableFrom(type) ||
70             typeof(Pointer).IsAssignableFrom(type) ||
71             (type.HasElementType && ExcludeType(type.GetElementType()));
72    }
73    private static IEnumerable<object> GetChildObjects(object obj, HashSet<string> excludedMembers, bool excludeStaticMembers) {
74      Type type = obj.GetType();
75
76      if (type.IsSubclassOfRawGeneric(typeof(ThreadLocal<>))) {
77        PropertyInfo info = type.GetProperty("Value");
78        object value = info.GetValue(obj, null);
79        if (value != null) yield return value;
80      } else if (type.IsSubclassOfRawGeneric(typeof(Dictionary<,>)) ||
81           type.IsSubclassOfRawGeneric(typeof(SortedDictionary<,>)) ||
82           type.IsSubclassOfRawGeneric(typeof(SortedList<,>)) ||
83           obj is SortedList ||
84           obj is OrderedDictionary ||
85           obj is ListDictionary ||
86           obj is Hashtable) {
87        var dictionary = obj as IDictionary;
88        foreach (object value in dictionary.Keys)
89          yield return value;
90        foreach (object value in dictionary.Values)
91          yield return value;
92      } else if (type.IsArray || type.IsSubclassOfRawGeneric(typeof(HashSet<>))) {
93        var enumerable = obj as IEnumerable;
94        foreach (var value in enumerable)
95          yield return value;
96      } else {
97        foreach (FieldInfo f in type.GetAllFields()) {
98          if (excludedMembers.Contains(f.Name)) continue;
99          if (excludeStaticMembers && f.IsStatic) continue;
100          object fieldValue;
101          try {
102            fieldValue = f.GetValue(obj);
103          }
104          catch (SecurityException) {
105            continue;
106          }
107          yield return fieldValue;
108        }
109      }
110    }
111  }
112}
Note: See TracBrowser for help on using the repository browser.