private static bool HasRequiredAccess(PropertyInfo pi, PropertyAccessRequired access) { Throw.IfArgumentNull(pi, nameof(pi)); switch (access) { case PropertyAccessRequired.Any: return(true); case PropertyAccessRequired.All: return(pi.CanRead && pi.CanWrite); case PropertyAccessRequired.Get: return(pi.CanRead); case PropertyAccessRequired.Set: return(pi.CanWrite); default: throw new ArgumentOutOfRangeException("access"); } }
/// <summary> /// Searches recursively through an object tree for property information. /// </summary> /// <param name="propertyName">The name of the property to search for.</param> /// <param name="access">The required property access.</param> /// <returns>PropertyInfo of the specified property if it can find it otherwise returns null.</returns> public static PropertyInfo GetPropertyInfo(this Type type, string propertyName, PropertyAccessRequired access) { return(GetPropertyInfo(type, propertyName, null, access)); }
/// <summary> /// Searches recursively through an object tree for property information. /// </summary> /// <param name="type">The type of the object to get the property from.</param> /// <param name="propertyName">The name of the property to search for.</param> /// <param name="propertyType">The type of the property to search for.</param> /// <param name="access">The required property access.</param> /// <returns>PropertyInfo of the specified property if it can find it otherwise returns null.</returns> public static PropertyInfo GetPropertyInfo(this Type type, string propertyName, Type propertyType, PropertyAccessRequired access) { Throw.IfArgumentNullOrEmpty(propertyName, nameof(propertyName)); var pi = (propertyType != null) ? type.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static, null, propertyType, new Type[0], null) : type.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static); var hasNoAccess = (pi != null && !HasRequiredAccess(pi, access)); if (pi == null || hasNoAccess) { if (type.BaseType != null) { pi = GetPropertyInfo(type.BaseType, propertyName, propertyType, access); } } return(pi); }