Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Benchmarking/sources/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 6987

Last change on this file since 6987 was 6891, checked in by abeham, 13 years ago

#1619, #1628

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