繁体   English   中英

将传递给IsValid方法的对象转换为适当的类型

[英]Cast to the appropriate type an object passed to IsValid method

版:

我出于存档的目的留了这个问题,但是我应该删除它。 这完全是我的错,我做错了几件事。 首先,我重用了RequiredIf验证中的代码,但是我应该删除_innerAttribute和与之相关的最内部的如果我忘记做的事情。 最主要的是,我试图将枚举与字符串进行比较,这就是失败的原因,但是如果我将适当的枚举成员传递给构造函数,代码实际上可以正常工作。 我完全误解了对象,演员的行为...

版本结束

我正在尝试编写一个自定义验证属性,如果另一个字段不为null,则该属性不允许将字段设置为特定值。 我已经写了这个(我省略了实现IClientVAlidatable的部分)

public class NotAllowedIfNotNullAttribute : ValidationAttribute, IClientValidatable
{
    private readonly RequiredAttribute _innerAttribute = new RequiredAttribute();

    public string DependentProperty { get; set; }
    public object NotAllowedValue { get; set; }

    public NotAllowedIfNotNullAttribute(string dependentProperty, object notAllowedValue)
    {
        DependentProperty = dependentProperty;
        NotAllowedValue = notAllowedValue;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var typedValue = CastValue(value, _valueType)
        ;
        var containerType = validationContext.ObjectInstance.GetType();

        var field = containerType.GetProperty(DependentProperty);

        if (field != null)
        {
            var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);

            if ((dependentvalue != null && value.Equals(NotAllowedValue)))
            {
                if (!_innerAttribute.IsValid(value))
                    return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
            }
        }

        return ValidationResult.Success;
    }
    //.....
}

我的问题是value.Equals(NotAllowedValue) ,如何将值转换为notAllowedValue类型? 我试图通过类型作为参数,但由于目前还没有运气,我需要在这种方法上做更多的工作

谢谢!

也许您应该尝试使用模板?

public class NotAllowedIfNotNullAttribute<T> : ValidationAttribute, IClientValidatable
    {
        private readonly RequiredAttribute _innerAttribute = new RequiredAttribute();

        public string DependentProperty { get; set; }
        public T NotAllowedValue { get; set; }

        public NotAllowedIfNotNullAttribute(string dependentProperty, T notAllowedValue)
        {
            DependentProperty = dependentProperty;
            NotAllowedValue = notAllowedValue;
        }

        protected override ValidationResult IsValid(T value, ValidationContext validationContext)
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM