Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1522: Replaced recursive object graph traversing with a linear solution using a stack to avoid stack overflows.

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