Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12939 was 12012, checked in by ascheibe, 10 years ago

#2212 merged r12008, r12009, r12010 back into trunk

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