Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 8418

Last change on this file since 8418 was 8206, checked in by gkronber, 12 years ago

#1847: merged r8084:8205 from trunk into GP move operators branch

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