CSharp examples for System.Reflection:Type
Is Simple Interface Type
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;/* w w w. ja v a 2 s. c o m*/ using System.Globalization; using System.Collections.Generic; using System; public class Main{ public static bool IsSimpleInterface(this Type t) { // not an interface? bail if (!t.IsInterface()) return false; // not public? bail if (!t.IsPublic()) return false; var members = t.GetAllInterfaceMembers(); var mtds = members.OfType<MethodInfo>().ToList(); var props = members.OfType<PropertyInfo>().ToList(); // something weird here, bail if (mtds.Count + props.Count != members.Count) return false; // any methods that aren't property accessors? bail if (mtds.Any(m => !props.Any(p => p.GetMethod == m || p.SetMethod == m))) return false; // define a property that takes parameters? bail if (props.Any(p => p.GetIndexParameters().Length != 0)) return false; return true; } public static bool IsInterface(this Type type) { var info = type.GetTypeInfo(); return info.IsInterface; } public static bool IsPublic(this Type type) { var info = type.GetTypeInfo(); return info.IsPublic; } 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 List<MemberInfo> GetAllInterfaceMembers(this Type t) { if (!t.IsInterface()) throw new Exception("Expected interface, found: " + t); var pending = new Stack<Type>(); pending.Push(t); var ret = new List<MemberInfo>(); while (pending.Count > 0) { var current = pending.Pop(); ret.AddRange(current.GetMembers()); if (current.BaseType() != null) { pending.Push(current.BaseType()); } current.GetInterfaces().ForEach(i => pending.Push(i)); } return ret; } }