using System.Reflection; using Quadarax.Foundation.Core.Reflection; namespace qdr.fnd.core.test.Utils { public static class ReflectionUtils { #region *** Properties operations *** public static bool HasProperty(Type type, string propertyName, bool includeInternals = false) { return GetProperty(type, propertyName, includeInternals)!=null; } public static bool HasPropertySetter(Type type, string propertyName, bool includeInternals = false) { var pinfo = GetProperty(type, propertyName, includeInternals); if (pinfo != null) { return pinfo.CanWrite; } throw new InvalidOperationException($"Cannot find property '{propertyName}' in type '{type.Name}'."); } public static bool HasPropertyGetter(Type type, string propertyName, bool includeInternals = false) { var pinfo = GetProperty(type, propertyName, includeInternals); if (pinfo != null) { return pinfo.CanRead; } throw new InvalidOperationException($"Cannot find property '{propertyName}' in type '{type.Name}'."); } public static PropertyInfo? GetProperty(Type type, string propertyName, bool includeInternals = false) { if (type == null) throw new ArgumentNullException(nameof(type)); if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException(nameof(propertyName)); var bindings = includeInternals ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic : BindingFlags.Instance | BindingFlags.Public; return type.GetProperties(bindings).FirstOrDefault(x=>string.Equals(x.Name, propertyName, StringComparison.InvariantCulture)); } public static TAttribute? GetPropertyAttribute(Type type, string propertyName, bool includeInherited = false) where TAttribute : Attribute { var pinfo = GetProperty(type, propertyName, true); if (pinfo != null) { return AttributeQuery.Find(pinfo, includeInherited); } throw new InvalidOperationException($"Cannot find property '{propertyName}' in type '{type.Name}'."); } public static bool HasPropertyAttribute(Type type, string propertyName, bool includeInherited = false) where TAttribute : Attribute { return GetPropertyAttribute(type, propertyName, includeInherited)!=null; } #endregion #region *** Class operations *** public static bool HasInterface(Type type, Type interfaceType) { if (type == null) throw new ArgumentNullException(nameof(type)); if (interfaceType == null) throw new ArgumentNullException(nameof(interfaceType)); return type.IsAssignableFrom(interfaceType); } public static bool HasInterfaceAll(Type type, params Type[] interfaceTypes) { var result = true; foreach (var interfaceType in interfaceTypes) { result = result && HasInterface(type, interfaceType); } return result; } public static bool HasInterfaceAny(Type type, params Type[] interfaceTypes) { var result = false; foreach (var interfaceType in interfaceTypes) { result = result || HasInterface(type, interfaceType); } return result; } #endregion } }