Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 17960

Last change on this file since 17960 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 5.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Namespace == "System.Net.Sockets" ||
88             (type.HasElementType && ExcludeType(type.GetElementType()));
89    }
90
91    private static IEnumerable<object> GetChildObjects(object obj, HashSet<object> excludedMembers, bool excludeStaticMembers, Dictionary<Type, FieldInfo[]> fieldInfos) {
92      Type type = obj.GetType();
93
94      if (type.IsSubclassOfRawGeneric(typeof(ThreadLocal<>))) {
95        PropertyInfo info = type.GetProperty("Value");
96        object value = info.GetValue(obj, null);
97        if (value != null && !excludedMembers.Contains(value))
98          yield return value;
99      } else if (type.IsSubclassOfRawGeneric(typeof(Dictionary<,>)) ||
100           type.IsSubclassOfRawGeneric(typeof(SortedDictionary<,>)) ||
101           type.IsSubclassOfRawGeneric(typeof(SortedList<,>)) ||
102           obj is SortedList ||
103           obj is OrderedDictionary ||
104           obj is ListDictionary ||
105           obj is Hashtable) {
106        var dictionary = obj as IDictionary;
107        foreach (object value in dictionary.Keys) {
108          if (excludedMembers.Contains(value)) continue;
109          yield return value;
110        }
111        foreach (object value in dictionary.Values) {
112          if (excludedMembers.Contains(value)) continue;
113          yield return value;
114        }
115      } else if (type.IsArray || type.IsSubclassOfRawGeneric(typeof(HashSet<>))) {
116        var enumerable = obj as IEnumerable;
117        foreach (var value in enumerable) {
118          if (excludedMembers.Contains(value)) continue;
119          yield return value;
120        }
121      } else {
122        FieldInfo[] fieldInfo;
123        if (!fieldInfos.TryGetValue(type, out fieldInfo)) {
124          fieldInfo = type.GetAllFields()
125            .Where(fi => !Attribute.IsDefined(fi, typeof(ExcludeFromObjectGraphTraversalAttribute)))
126            .ToArray();
127          fieldInfos.Add(type, fieldInfo);
128        }
129        foreach (FieldInfo f in fieldInfo) {
130          if (excludeStaticMembers && f.IsStatic) continue;
131          object fieldValue;
132          try {
133            fieldValue = f.GetValue(obj);
134          } catch (SecurityException) {
135            continue;
136          }
137          if (excludedMembers.Contains(fieldValue)) continue;
138          yield return fieldValue;
139        }
140      }
141    }
142  }
143}
Note: See TracBrowser for help on using the repository browser.