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

Last change on this file since 13510 was 13510, checked in by pfleck, 4 years ago

#2557
Fixed wrong excluding of types in object graph traversal (no members were traversed any more).
Added a unit test that verifies that GetObjectGraphObjects yields a reasonable number of objects.

File size: 5.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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<T> ToEnumerable<T>(this T obj) {
34      yield return obj;
35    }
36
37    public static IEnumerable<object> GetObjectGraphObjects(this object obj, HashSet<object> excludedMembers = null, bool excludeStaticMembers = false) {
38      if (obj == null) return Enumerable.Empty<object>();
39      if (excludedMembers == null) excludedMembers = new HashSet<object>();
40      var fieldInfos = new Dictionary<Type, FieldInfo[]>();
41
42      var objects = new HashSet<object>();
43      var stack = new Stack<object>();
44
45      stack.Push(obj);
46      while (stack.Count > 0) {
47        object current = stack.Pop();
48        objects.Add(current);
49
50        foreach (object o in GetChildObjects(current, excludedMembers, excludeStaticMembers, fieldInfos)) {
51          if (o == null) continue;
52          if (ExcludeType(o.GetType())) continue;
53          if (objects.Contains(o)) continue;
54          stack.Push(o);
55        }
56      }
57
58      return objects;
59    }
60
61    /// <summary>
62    /// Types not collected:
63    ///   * System.Delegate
64    ///   * System.Reflection.Pointer
65    ///   * Primitives (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single)
66    ///   * string, decimal, DateTime
67    ///   * Arrays of types not collected
68    ///   * All types from System.Reflection.Emit
69    /// </summary>
70    private static bool ExcludeType(Type type) {
71      return type.IsPrimitive ||
72             type == typeof(string) ||
73             type == typeof(string[]) ||
74             type == typeof(decimal) ||
75             type == typeof(decimal[]) ||
76             type == typeof(DateTime) ||
77             type == typeof(DateTime[]) ||
78             typeof(Delegate).IsAssignableFrom(type) ||
79             typeof(Pointer).IsAssignableFrom(type) ||
80             type.Namespace == "System.Reflection.Emit" ||
81             (type.HasElementType && ExcludeType(type.GetElementType()));
82    }
83
84    private static IEnumerable<object> GetChildObjects(object obj, HashSet<object> excludedMembers, bool excludeStaticMembers, Dictionary<Type, FieldInfo[]> fieldInfos) {
85      Type type = obj.GetType();
86
87      if (type.IsSubclassOfRawGeneric(typeof(ThreadLocal<>))) {
88        PropertyInfo info = type.GetProperty("Value");
89        object value = info.GetValue(obj, null);
90        if (value != null && !excludedMembers.Contains(value))
91          yield return value;
92      } else if (type.IsSubclassOfRawGeneric(typeof(Dictionary<,>)) ||
93           type.IsSubclassOfRawGeneric(typeof(SortedDictionary<,>)) ||
94           type.IsSubclassOfRawGeneric(typeof(SortedList<,>)) ||
95           obj is SortedList ||
96           obj is OrderedDictionary ||
97           obj is ListDictionary ||
98           obj is Hashtable) {
99        var dictionary = obj as IDictionary;
100        foreach (object value in dictionary.Keys) {
101          if (excludedMembers.Contains(value)) continue;
102          yield return value;
103        }
104        foreach (object value in dictionary.Values) {
105          if (excludedMembers.Contains(value)) continue;
106          yield return value;
107        }
108      } else if (type.IsArray || type.IsSubclassOfRawGeneric(typeof(HashSet<>))) {
109        var enumerable = obj as IEnumerable;
110        foreach (var value in enumerable) {
111          if (excludedMembers.Contains(value)) continue;
112          yield return value;
113        }
114      } else {
115        if (!fieldInfos.ContainsKey(type))
116          fieldInfos[type] = type.GetAllFields().ToArray();
117        foreach (FieldInfo f in fieldInfos[type]) {
118          if (excludeStaticMembers && f.IsStatic) continue;
119          object fieldValue;
120          try {
121            fieldValue = f.GetValue(obj);
122          }
123          catch (SecurityException) {
124            continue;
125          }
126          if (excludedMembers.Contains(fieldValue)) continue;
127          yield return fieldValue;
128        }
129      }
130    }
131  }
132}
Note: See TracBrowser for help on using the repository browser.