Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Async/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 15280

Last change on this file since 15280 was 15280, checked in by abeham, 7 years ago

#2258: merged r13329:14000 from trunk into branch

File size: 5.2 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    ///   * System.RuntimeType
66    ///   * Primitives (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single)
67    ///   * string, decimal, DateTime
68    ///   * Arrays of types not collected
69    ///   * All types from System.Reflection.Emit
70    /// </summary>
71    private static bool ExcludeType(Type type) {
72      return type.IsPrimitive ||
73             type == typeof(string) ||
74             type == typeof(string[]) ||
75             type == typeof(decimal) ||
76             type == typeof(decimal[]) ||
77             type == typeof(DateTime) ||
78             type == typeof(DateTime[]) ||
79             typeof(Delegate).IsAssignableFrom(type) ||
80             typeof(Pointer).IsAssignableFrom(type) ||
81             type.Namespace == "System.Reflection.Emit" ||
82             type.Assembly.GetName().Name == "System.Runtime.Serialization" ||
83             typeof(TypeInfo).IsAssignableFrom(type) ||
84             (type.HasElementType && ExcludeType(type.GetElementType()));
85    }
86
87    private static IEnumerable<object> GetChildObjects(object obj, HashSet<object> excludedMembers, bool excludeStaticMembers, Dictionary<Type, FieldInfo[]> fieldInfos) {
88      Type type = obj.GetType();
89
90      if (type.IsSubclassOfRawGeneric(typeof(ThreadLocal<>))) {
91        PropertyInfo info = type.GetProperty("Value");
92        object value = info.GetValue(obj, null);
93        if (value != null && !excludedMembers.Contains(value))
94          yield return value;
95      } else if (type.IsSubclassOfRawGeneric(typeof(Dictionary<,>)) ||
96           type.IsSubclassOfRawGeneric(typeof(SortedDictionary<,>)) ||
97           type.IsSubclassOfRawGeneric(typeof(SortedList<,>)) ||
98           obj is SortedList ||
99           obj is OrderedDictionary ||
100           obj is ListDictionary ||
101           obj is Hashtable) {
102        var dictionary = obj as IDictionary;
103        foreach (object value in dictionary.Keys) {
104          if (excludedMembers.Contains(value)) continue;
105          yield return value;
106        }
107        foreach (object value in dictionary.Values) {
108          if (excludedMembers.Contains(value)) continue;
109          yield return value;
110        }
111      } else if (type.IsArray || type.IsSubclassOfRawGeneric(typeof(HashSet<>))) {
112        var enumerable = obj as IEnumerable;
113        foreach (var value in enumerable) {
114          if (excludedMembers.Contains(value)) continue;
115          yield return value;
116        }
117      } else {
118        if (!fieldInfos.ContainsKey(type))
119          fieldInfos[type] = type.GetAllFields().ToArray();
120        foreach (FieldInfo f in fieldInfos[type]) {
121          if (excludeStaticMembers && f.IsStatic) continue;
122          object fieldValue;
123          try {
124            fieldValue = f.GetValue(obj);
125          }
126          catch (SecurityException) {
127            continue;
128          }
129          if (excludedMembers.Contains(fieldValue)) continue;
130          yield return fieldValue;
131        }
132      }
133    }
134  }
135}
Note: See TracBrowser for help on using the repository browser.