示例#1
0
        private HashSet <object> GetAllowedValues(ValidationContext validationContext)
        {
            if (AllowedValuesProvider is null)
            {
                return(AllowedValues.ToHashSet());
            }

            var instance = validationContext.ObjectInstance;
            var type     = instance.GetType();
            var member   = type.GetMember(
                AllowedValuesProvider,
                MemberTypes.Field | MemberTypes.Property | MemberTypes.Method,
                BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static
                )
                           .FirstOrDefault();

            if (member is null)
            {
                throw new ArgumentException(
                          $"{nameof(AllowedValuesProvider)} must reference a field or method in {type.FullName}",
                          AllowedValuesProvider
                          );
            }

            var providedValues = member.MemberType switch
            {
                MemberTypes.Field => ((FieldInfo)member).GetValue(instance),
                MemberTypes.Property => ((PropertyInfo)member).GetValue(instance),
                MemberTypes.Method => ((MethodInfo)member).Invoke(instance, new object?[] { }),
                _ => throw new ArgumentOutOfRangeException(
                          $"{nameof(AllowedValuesProvider)} is not a valid member on {type.FullName}",
                          AllowedValuesProvider
                          )
            };

            if (providedValues is not IEnumerable <object> providedAllowedValues)
            {
                throw new ArgumentException(
                          $"{nameof(AllowedValuesProvider)} on {type.FullName} must implement {nameof(IEnumerable)}",
                          AllowedValuesProvider
                          );
            }

            return(AllowedValues
                   .Concat(providedAllowedValues)
                   .ToHashSet());
        }
    }