Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14251 was 14185, checked in by swagner, 8 years ago

#2526: Updated year of copyrights in license headers

File size: 5.4 KB
RevLine 
[6103]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 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 {
[14032]32
[14144]33  [AttributeUsage(AttributeTargets.Field)]
[14032]34  // this attribute can be used to mark fields that should be excluded from object graph traversal
35  public class ExcludeFromObjectGraphTraversalAttribute : Attribute {
36  }
37
[6103]38  public static class ObjectExtensions {
[8128]39    public static IEnumerable<T> ToEnumerable<T>(this T obj) {
40      yield return obj;
41    }
42
[8212]43    public static IEnumerable<object> GetObjectGraphObjects(this object obj, HashSet<object> excludedMembers = null, bool excludeStaticMembers = false) {
[6380]44      if (obj == null) return Enumerable.Empty<object>();
[8212]45      if (excludedMembers == null) excludedMembers = new HashSet<object>();
[9855]46      var fieldInfos = new Dictionary<Type, FieldInfo[]>();
[6380]47
[6103]48      var objects = new HashSet<object>();
[6380]49      var stack = new Stack<object>();
50
51      stack.Push(obj);
52      while (stack.Count > 0) {
53        object current = stack.Pop();
54        objects.Add(current);
55
[9855]56        foreach (object o in GetChildObjects(current, excludedMembers, excludeStaticMembers, fieldInfos)) {
[8310]57          if (o == null) continue;
58          if (ExcludeType(o.GetType())) continue;
59          if (objects.Contains(o)) continue;
60          stack.Push(o);
[6380]61        }
62      }
63
[6103]64      return objects;
65    }
[6891]66
[6192]67    /// <summary>
68    /// Types not collected:
69    ///   * System.Delegate
[6205]70    ///   * System.Reflection.Pointer
[6192]71    ///   * Primitives (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single)
[7796]72    ///   * string, decimal, DateTime
[6205]73    ///   * Arrays of types not collected
[13494]74    ///   * All types from System.Reflection.Emit
[6192]75    /// </summary>
[6380]76    private static bool ExcludeType(Type type) {
77      return type.IsPrimitive ||
78             type == typeof(string) ||
[8310]79             type == typeof(string[]) ||
[6380]80             type == typeof(decimal) ||
[8310]81             type == typeof(decimal[]) ||
[7796]82             type == typeof(DateTime) ||
[8310]83             type == typeof(DateTime[]) ||
[6380]84             typeof(Delegate).IsAssignableFrom(type) ||
85             typeof(Pointer).IsAssignableFrom(type) ||
[13510]86             type.Namespace == "System.Reflection.Emit" ||
[6380]87             (type.HasElementType && ExcludeType(type.GetElementType()));
88    }
[8212]89
[9855]90    private static IEnumerable<object> GetChildObjects(object obj, HashSet<object> excludedMembers, bool excludeStaticMembers, Dictionary<Type, FieldInfo[]> fieldInfos) {
[6192]91      Type type = obj.GetType();
[6181]92
[6500]93      if (type.IsSubclassOfRawGeneric(typeof(ThreadLocal<>))) {
94        PropertyInfo info = type.GetProperty("Value");
95        object value = info.GetValue(obj, null);
[8310]96        if (value != null && !excludedMembers.Contains(value))
[8212]97          yield return value;
[6500]98      } else if (type.IsSubclassOfRawGeneric(typeof(Dictionary<,>)) ||
99           type.IsSubclassOfRawGeneric(typeof(SortedDictionary<,>)) ||
100           type.IsSubclassOfRawGeneric(typeof(SortedList<,>)) ||
101           obj is SortedList ||
102           obj is OrderedDictionary ||
103           obj is ListDictionary ||
104           obj is Hashtable) {
[6205]105        var dictionary = obj as IDictionary;
[8212]106        foreach (object value in dictionary.Keys) {
[8310]107          if (excludedMembers.Contains(value)) continue;
[6380]108          yield return value;
[8212]109        }
110        foreach (object value in dictionary.Values) {
[8310]111          if (excludedMembers.Contains(value)) continue;
[6380]112          yield return value;
[8212]113        }
[6205]114      } else if (type.IsArray || type.IsSubclassOfRawGeneric(typeof(HashSet<>))) {
115        var enumerable = obj as IEnumerable;
[8212]116        foreach (var value in enumerable) {
[8310]117          if (excludedMembers.Contains(value)) continue;
[6380]118          yield return value;
[8212]119        }
[6380]120      } else {
[14144]121        FieldInfo[] fieldInfo;
122        if (!fieldInfos.TryGetValue(type, out fieldInfo)) {
123          fieldInfo = type.GetAllFields()
124            .Where(fi => !Attribute.IsDefined(fi, typeof(ExcludeFromObjectGraphTraversalAttribute)))
[14032]125            .ToArray();
[14144]126          fieldInfos.Add(type, fieldInfo);
127        }
128        foreach (FieldInfo f in fieldInfo) {
[6891]129          if (excludeStaticMembers && f.IsStatic) continue;
[7139]130          object fieldValue;
131          try {
132            fieldValue = f.GetValue(obj);
[14144]133          } catch (SecurityException) {
[7139]134            continue;
135          }
[8310]136          if (excludedMembers.Contains(fieldValue)) continue;
[7139]137          yield return fieldValue;
[6380]138        }
[6192]139      }
[6103]140    }
141  }
142}
Note: See TracBrowser for help on using the repository browser.