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

Last change on this file since 14032 was 14032, checked in by gkronber, 5 years ago

#2626: reverted changes from r13998 and introduce a new attribute (ExcludeFromObjectGraphTraversalAttribute) which can be used to mark fields that should be excluded from object graph traversal

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