using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class ReflectionUtility { public static IEnumerable GetAllFields(object target, Func predicate) { List types = new List() { target.GetType() }; while (Enumerable.Last(types).BaseType != null) types.Add(Enumerable.Last(types).BaseType); for (int i = types.Count - 1; i >= 0; i--) { IEnumerable fieldInfos = types[i] .GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly) .Where(predicate); foreach (var fieldInfo in fieldInfos) yield return fieldInfo; } } public static IEnumerable GetAllProperties(object target, Func predicate) { List types = new List() { target.GetType() }; while (Enumerable.Last(types).BaseType != null) types.Add(Enumerable.Last(types).BaseType); for (int i = types.Count - 1; i >= 0; i--) { IEnumerable propertyInfos = types[i] .GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly) .Where(predicate); foreach (var propertyInfo in propertyInfos) yield return propertyInfo; } } public static IEnumerable GetAllMethods(object target, Func predicate) { IEnumerable methodInfos = target.GetType() .GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public) .Where(predicate); return methodInfos; } public static FieldInfo GetField(object target, string fieldName) => GetAllFields(target, f => f.Name.Equals(fieldName, StringComparison.InvariantCulture)).FirstOrDefault(); public static PropertyInfo GetProperty(object target, string propertyName) => GetAllProperties(target, p => p.Name.Equals(propertyName, StringComparison.InvariantCulture)).FirstOrDefault(); public static MethodInfo GetMethod(object target, string methodName) => GetAllMethods(target, m => m.Name.Equals(methodName, StringComparison.InvariantCulture)).FirstOrDefault(); }