且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用System.Configuration验证程序进行双重验证

更新时间:2023-01-29 17:53:40

我需要为自己的项目使用float验证程序,并找到了您的问题. 这就是我制作验证器的方式.当/如果使用它,应该记住在用于注释属性的ConfigurationPropertyAttribute上设置默认值.

I needed a float validator for my own project, and found your question. This is how I made my validator. When/if you use it, you should remember to set a default value on the ConfigurationPropertyAttribute that you annotate the property with.

感谢KasperVidebæk发现我的错误: ConfigurationValidatorBase验证方法会接收默认值

Thanks to Kasper Videbæk for finding my mistake: ConfigurationValidatorBase validate method receives default value

class DoubleValidator : ConfigurationValidatorBase
{
    public double MinValue { get; private set; }
    public double MaxValue { get; private set; }

    public DoubleValidator(double minValue, double maxValue)
    {
        MinValue = minValue;
        MaxValue = maxValue;
    }

    public override bool CanValidate(Type type)
    {
        return type == typeof(double);
    }

    public override void Validate(object obj)
    {
        double value;
        try
        {
            value = Convert.ToDouble(obj);
        }
        catch (Exception)
        {
            throw new ArgumentException();
        }

        if (value < MinValue)
        {
            throw new ConfigurationErrorsException($"Value too low, minimum value allowed: {MinValue}");
        }

        if (value > MaxValue)
        {
            throw new ConfigurationErrorsException($"Value too high, maximum value allowed: {MaxValue}");
        }
    }
}

要在配置属性上使用的属性

The attribute to use on the configurationproperty

class DoubleValidatorAttribute : ConfigurationValidatorAttribute
{
    public double MinValue { get; set; }
    public double MaxValue { get; set; }

    public DoubleValidatorAttribute(double minValue, double maxValue)
    {
        MinValue = minValue;
        MaxValue = maxValue;
    }

    public override ConfigurationValidatorBase ValidatorInstance => new DoubleValidator(MinValue, MaxValue);
}