Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2901_StaticSelectionMethods/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 17442

Last change on this file since 17442 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 5.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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(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        FieldInfo[] fieldInfo;
122        if (!fieldInfos.TryGetValue(type, out fieldInfo)) {
123          fieldInfo = type.GetAllFields()
124            .Where(fi => !Attribute.IsDefined(fi, typeof(ExcludeFromObjectGraphTraversalAttribute)))
125            .ToArray();
126          fieldInfos.Add(type, fieldInfo);
127        }
128        foreach (FieldInfo f in fieldInfo) {
129          if (excludeStaticMembers && f.IsStatic) continue;
130          object fieldValue;
131          try {
132            fieldValue = f.GetValue(obj);
133          } catch (SecurityException) {
134            continue;
135          }
136          if (excludedMembers.Contains(fieldValue)) continue;
137          yield return fieldValue;
138        }
139      }
140    }
141  }
142}
Note: See TracBrowser for help on using the repository browser.