Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7139 was 7139, checked in by epitzer, 12 years ago

#1701 Catch SecurityExceptions while accessing fields during object graph traversal.

File size: 4.1 KB
RevLine 
[6103]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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;
[6205]23using System.Collections;
[6103]24using System.Collections.Generic;
[6205]25using System.Collections.Specialized;
[6380]26using System.Linq;
[6103]27using System.Reflection;
[7139]28using System.Security;
[6500]29using System.Threading;
[6103]30
31namespace HeuristicLab.Common {
32  public static class ObjectExtensions {
[6891]33    public static IEnumerable<object> GetObjectGraphObjects(this object obj, bool excludeStaticMembers = false) {
[6380]34      if (obj == null) return Enumerable.Empty<object>();
35
[6103]36      var objects = new HashSet<object>();
[6380]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
[6891]44        foreach (object o in GetChildObjects(current, excludeStaticMembers)) {
[6380]45          if (o != null && !objects.Contains(o) && !ExcludeType(o.GetType()))
46            stack.Push(o);
47        }
48      }
49
[6103]50      return objects;
51    }
[6891]52
[6192]53    /// <summary>
54    /// Types not collected:
55    ///   * System.Delegate
[6205]56    ///   * System.Reflection.Pointer
[6192]57    ///   * Primitives (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single)
58    ///   * string, decimal
[6205]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.
[6192]63    /// </summary>
[6380]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    }
[6891]72    private static IEnumerable<object> GetChildObjects(object obj, bool excludeStaticMembers) {
[6192]73      Type type = obj.GetType();
[6181]74
[6500]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) {
[6205]86        var dictionary = obj as IDictionary;
[6201]87        foreach (object value in dictionary.Keys)
[6380]88          yield return value;
[6201]89        foreach (object value in dictionary.Values)
[6380]90          yield return value;
[6205]91      } else if (type.IsArray || type.IsSubclassOfRawGeneric(typeof(HashSet<>))) {
92        var enumerable = obj as IEnumerable;
93        foreach (var value in enumerable)
[6380]94          yield return value;
95      } else {
96        foreach (FieldInfo f in type.GetAllFields()) {
[6891]97          if (excludeStaticMembers && f.IsStatic) continue;
[7139]98          object fieldValue;
99          try {
100            fieldValue = f.GetValue(obj);
101          } catch (SecurityException) {
102            continue;
103          }
104          yield return fieldValue;
[6380]105        }
[6192]106      }
[6103]107    }
108  }
109}
Note: See TracBrowser for help on using the repository browser.