Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1569: Added special handling for ThreadLocal<> in Object.GetObjectGraphObjects().

File size: 3.7 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) {
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)) {
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(ThreadLocal<>))) {
74        PropertyInfo info = type.GetProperty("Value");
75        object value = info.GetValue(obj, null);
76        if (value != null) yield return value;
77      } else if (type.IsSubclassOfRawGeneric(typeof(Dictionary<,>)) ||
78           type.IsSubclassOfRawGeneric(typeof(SortedDictionary<,>)) ||
79           type.IsSubclassOfRawGeneric(typeof(SortedList<,>)) ||
80           obj is SortedList ||
81           obj is OrderedDictionary ||
82           obj is ListDictionary ||
83           obj is Hashtable) {
84        var dictionary = obj as IDictionary;
85        foreach (object value in dictionary.Keys)
86          yield return value;
87        foreach (object value in dictionary.Values)
88          yield return value;
89      } else if (type.IsArray || type.IsSubclassOfRawGeneric(typeof(HashSet<>))) {
90        var enumerable = obj as IEnumerable;
91        foreach (var value in enumerable)
92          yield return value;
93      } else {
94        foreach (FieldInfo f in type.GetAllFields()) {
95          yield return f.GetValue(obj);
96        }
97      }
98    }
99  }
100}
Note: See TracBrowser for help on using the repository browser.