CSharp examples for System.Reflection:Type
Involved Types
using System.Threading.Tasks; using System.Text; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Reflection.Emit; using System.Reflection; using System.Linq; using System.IO;//from w ww . ja va2s .c o m using System.Globalization; using System.Collections.Generic; using System; public class Main{ public static List<Type> InvolvedTypes(this Type t) { var ret = new List<Type>(); var pending = new Stack<Type>(); pending.Push(t); while (pending.Count > 0) { var cur = pending.Pop(); if (!ret.Contains(cur)) { ret.Add(cur); } else { continue; } if (cur.IsNullableType()) { var inner = Nullable.GetUnderlyingType(cur); pending.Push(inner); continue; } if (cur.IsListType()) { var elem = cur.GetListInterface().GetGenericArguments()[0]; pending.Push(elem); continue; } if (cur.IsDictionaryType()) { var key = cur.GetDictionaryInterface().GetGenericArguments()[0]; var val = cur.GetDictionaryInterface().GetGenericArguments()[1]; pending.Push(key); pending.Push(val); continue; } if (cur.IsEnumerableType()) { var val = cur.GetEnumerableInterface().GetGenericArguments()[0]; pending.Push(val); continue; } cur.GetFields().ForEach(f => pending.Push(f.FieldType)); cur.GetProperties().Where(p => p.GetMethod != null && p.GetMethod.GetParameters().Length == 0).ForEach(p => pending.Push(p.PropertyType)); } return ret; } public static Type GetEnumerableInterface(this Type t) { return t.GetContainerInterface(typeof(IEnumerable<>)); } public static Type GetDictionaryInterface(this Type t) { return t.GetContainerInterface(typeof(IDictionary<,>)); } public static void ForEach<T>(this IEnumerable<T> e, Action<T> func) { foreach (var x in e) { func(x); } } public static Type GetUnderlyingType(this Type t) { return Nullable.GetUnderlyingType(t); } public static bool IsEnumerableType(this Type t) { return t.IsContainerType(typeof(IEnumerable<>)); } public static Type GetListInterface(this Type t) { return t.GetContainerInterface(typeof(IList<>)); } public static bool IsNullableType(this Type t) { var underlying = GetUnderlyingType(t); return underlying != null; } public static MethodInfo GetMethod(this Type type, string name, BindingFlags flags, Type[] parameterTypes) { var info = type.GetTypeInfo(); var mtds = info.GetMethods(flags).Where(m => m.Name == name); foreach (var mtd in mtds) { var ps = mtd.GetParameters(); if (ps.Length != parameterTypes.Length) continue; var allMatch = true; for (var i = 0; i < ps.Length; i++) { var p = ps[i].ParameterType; var pt = parameterTypes[i]; if (p != pt) { allMatch = false; } } if (allMatch) { return mtd; } } return null; } public static bool IsListType(this Type t) { return t.IsContainerType(typeof(IList<>)); } public static bool IsDictionaryType(this Type t) { return t.IsContainerType(typeof(IDictionary<,>)); } }