范围数据注释似乎无法在 .Net 3.5 中工作

发布于 2024-09-14 03:25:33 字数 1174 浏览 6 评论 0原文

使用.Net 3.5,

我在属性上有一个范围属性(System.ComponentModel.DataAnnotations)...

   [Range(0, 5, ErrorMessage = "Weight must be between 0 and 5")]
    public virtual double Weight{ get; set; }

并且我在类中有一个检查验证属性的 Validate 方法...

protected virtual void Validate()
{
    var type = this.GetType();
    foreach (var property in type.GetProperties())
    {
        foreach (ValidationAttribute attribute in 
            property.GetCustomAttributes(typeof(ValidationAttribute),true))
        {
            if(!attribute.IsValid(property.GetValue(this, null)))
            {
                BrokenRules.Add(attribute.ErrorMessage);
            }
        }
    }
}

    public virtual bool IsValid()
    {
        return GetBrokenRules().Count == 0;
    }

并且我有一个用于测试验证的 NUnit 测试... 必需的属性

[TestCase(-.1, Result = false)] // fails
[TestCase(0.0, Result = true)]
[TestCase(5.0, Result = true)]
[TestCase(5.1, Result = false)]  // fails
public bool ItValidatesWeight(double weight)
{
    _ornament.Weight = weight;
    return _ornament.IsValid();
}

工作正常,但在类和测试上正确,但 Range 属性却不然。有什么建议吗?

Using .Net 3.5

I have a Range Attributes (System.ComponentModel.DataAnnotations) on a Property...

   [Range(0, 5, ErrorMessage = "Weight must be between 0 and 5")]
    public virtual double Weight{ get; set; }

And I have a Validate method in the class that checks validation attributes...

protected virtual void Validate()
{
    var type = this.GetType();
    foreach (var property in type.GetProperties())
    {
        foreach (ValidationAttribute attribute in 
            property.GetCustomAttributes(typeof(ValidationAttribute),true))
        {
            if(!attribute.IsValid(property.GetValue(this, null)))
            {
                BrokenRules.Add(attribute.ErrorMessage);
            }
        }
    }
}

    public virtual bool IsValid()
    {
        return GetBrokenRules().Count == 0;
    }

And I have an NUnit test that tests the validation...

[TestCase(-.1, Result = false)] // fails
[TestCase(0.0, Result = true)]
[TestCase(5.0, Result = true)]
[TestCase(5.1, Result = false)]  // fails
public bool ItValidatesWeight(double weight)
{
    _ornament.Weight = weight;
    return _ornament.IsValid();
}

Required attributes are working properly but on the class and test correctly, but the Range attributes are not. Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

注定孤独终老 2024-09-21 03:25:33

它将属性解释为使用 int 重载。

它与:

[Range(0.0, 5.0, ErrorMessage = "Weight must be between 0 and 5")]
    public virtual double Weight{ get; set; }

It was interpreting the attribute as using the int overload.

It worked with:

[Range(0.0, 5.0, ErrorMessage = "Weight must be between 0 and 5")]
    public virtual double Weight{ get; set; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文