【问题标题】:c# conditional Required Attributec# 条件必需属性
【发布时间】:2018-05-03 05:20:58
【问题描述】:

如何将条件必需属性放入类中?我尝试了以下代码,但它不起作用。

public partial class Zone
{
    [RequireCondition ]
    public int LastCount { get; set; }
}
public class RequireCondition : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var Zone = (Zone)validationContext.ObjectInstance;
            if (Zone.LastCount < 1)
            {
                return new ValidationResult("Last Count value must be greater than one.");
            }
            else
           {
                return ValidationResult.Success;
           }
        }
    }

【问题讨论】:

  • “它不起作用”是什么意思?调试时发现了什么?
  • 条件不行,只要值小于1我仍然可以继续
  • Downvote reason - 请阅读,它具有教育意义。您可以通过在以var Zone = 开头的行放置断点并检查value 的值来找出value 的值。

标签: c# asp.net-web-api custom-attributes


【解决方案1】:

试试这个?

public partial class Zone
{
    [RequireCondition(1)]
    public int LastCount { get; set; }
}

public class RequireConditionAttribute : ValidationAttribute
 {
     private int _comparisonValue;

     public RequireCondition(int comparisonValue)
     {
        _comparisonValue = comparisonValue;
     }

     protected override ValidationResult IsValid(object value, ValidationContext validationContext)
      {              
        if (value is int && (int)value < comparisonValue)
            {
              return new ValidationResult($"{validationContext.DisplayName} value must be greater than one.");
            }

            return ValidationResult.Success;
        }
    }

【讨论】:

  • 嗨,出现错误,运算符'比较值)行中
猜你喜欢
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多