Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/Util.cs @ 1324

Last change on this file since 1324 was 1324, checked in by epitzer, 15 years ago

replace Functional with Linq

File size: 2.3 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Reflection;
5using System.Collections;
6
7namespace Persistence { 
8  public class InterfaceInstantiatior {
9    public static List<T> InstantiateAll<T>() {
10      return InstantiateAll<T>(Assembly.GetExecutingAssembly());
11    }
12    public static List<T> InstantiateAll<T>(Assembly a) {
13      List<T> instances = new List<T>();
14      foreach (Type t in a.GetTypes()) {
15        if (t.GetInterface(typeof(T).FullName) != null) {
16          ConstructorInfo ci = t.GetConstructor(new Type[] { });
17          if (ci != null) {
18            instances.Add((T)ci.Invoke(new object[] { }));
19          }
20        }
21      }
22      return instances;
23    }
24  }
25  public class Util {
26    public static string AutoFormat(object o) {
27      return AutoFormat(o, false);
28    }
29    public static string AutoFormat(object o, bool recursive) {
30      Dictionary<object, int> visitedObjects = new Dictionary<object,int>();
31      return AutoFormat(o, recursive, visitedObjects);
32    }
33    private static string AutoFormat(object o, bool recursive, Dictionary<object, int> visitedObjects) {
34      string s = o as string;
35      if (s != null)
36        return s;
37      if (o == null) {
38        return "<null>";
39      }
40      if (visitedObjects.ContainsKey(o)) {
41        return o.ToString();
42      } else {
43        visitedObjects.Add(o, 0);
44      }     
45      if (o.ToString() != o.GetType().ToString()) {
46        return o.ToString();
47      }
48      StringBuilder sb = new StringBuilder();
49      sb.Append(o.GetType().Name);
50      sb.Append("(");
51      foreach (MemberInfo mInfo in o.GetType().GetMembers(
52        BindingFlags.Public |
53        BindingFlags.NonPublic |
54        BindingFlags.Instance)) {
55        if (mInfo.MemberType == MemberTypes.Field) {
56          FieldInfo fInfo = (FieldInfo)mInfo;         
57          sb.Append(mInfo.Name);
58          sb.Append("=");         
59          if (recursive) {
60            sb.Append(AutoFormat(((FieldInfo)mInfo).GetValue(o), true, visitedObjects));
61          } else {
62            sb.Append(((FieldInfo)mInfo).GetValue(o));
63          }
64          sb.Append(", ");
65        }
66      }
67      sb.Remove(sb.Length - 2, 2);
68      sb.Append(")");
69      return sb.ToString();
70    }
71  }
72}
Note: See TracBrowser for help on using the repository browser.