Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 9793

Last change on this file since 9793 was 9363, checked in by spimming, 12 years ago

#1888:

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