反射检查参数值类型和设置值

时间:2013-09-07 04:50:13

标签: c# asp.net asp.net-mvc

有人可以告诉我如何检查参数“value”是否具有来自FileName对象的名为HttpPostedFileBase的属性,如果确实如此,则为其值设置value = FileName - - 在下面的代码中查看我的评论

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // get a reference to the property this validation depends upon
        var containerType = validationContext.ObjectInstance.GetType();
        var field = containerType.GetProperty(DependentProperty);

        if (field != null)
        {
            // get the value of the dependent property
            var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
            // trim spaces of dependent value
            if (dependentValue != null && dependentValue is string)
            {
                dependentValue = (dependentValue as string).Trim();

                if (!AllowEmptyStrings && (dependentValue as string).Length == 0)
                {
                    dependentValue = null;
                }
            }

            /* test value parameter here 
            if its has a property called FileName then 
            make value = FileName ;*/

            // compare the value against the target value
            if ((dependentValue == null && TargetValue == null) ||
                (dependentValue != null && (TargetValue.Equals("*") || dependentValue.Equals(TargetValue))))
            {
                // match => means we should try validating this field
                if (!_innerAttribute.IsValid(value))
                    // validation failed - return an error
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
            }
        }

        return ValidationResult.Success;
    }

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解你的问题,但是:

var valueType = value.GetType()
var fileNameProperty = valueType.GetProperty("FileName");
if(fileNameProperty != null)
    value = fileNameProperty.GetValue(value);