Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveHiveEngine/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 10568

Last change on this file since 10568 was 7259, checked in by swagner, 13 years ago

Updated year of copyrights to 2012 (#1716)

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