RangeAttribute不起作用

时间:2014-09-21 03:01:59

标签: c# .net vb.net winforms attributes

(我接受VB.NET或C#解决方案没有任何问题)

我创建了一个新的空WinForms项目,该内容用VB.NET编写,仅用于测试RangeAttribute,但范围和错误消息完全被忽略(任何错误):

Public Class Form1

    Private Shadows Sub Load() Handles MyBase.Load

        Dim Test As New Test With {.MyInt32 = Integer.MaxValue}

        MessageBox.Show(Test.MyInt32) ' Result: 2147483647

    End Sub

End Class

Public Class Test

    <System.ComponentModel.DataAnnotations.Range(1I, 10I, errormessage:="something")>
    Public Property MyInt32 As Integer
        Get
            Return Me._MyInt32
        End Get
        Set(ByVal value As Integer)
            Me._MyInt32 = value
        End Set
    End Property

    Private _MyInt32 As Integer = 0I

End Class

为什么会这样?

正在搜索替代解决方案我使用PostSharp创建了 Aspect ,如其中一个答案of this question所述,但我不喜欢这个解决方案,因为我不应该依赖第三方lib来做这件事,以防.NET Framework类库暴露出一种方法来做同样的事情(我认为更好'导致DateTime类型的属性重载等)。

2 个答案:

答案 0 :(得分:0)

难怪它不起作用,因为RangeAttribute不支持WinForms。您在命名空间 System.ComponentModel.DataAnnotations 中找到的所有内容都适用于Web应用程序。

  

“System.ComponentModel.DataAnnotations命名空间提供了用于为ASP.NET MVC和ASP.NET数据控件定义元数据的属性类。” - MSDN

答案 1 :(得分:0)

您只需要执行验证。虽然System.ComponentModel.DataAnnotations通常用于网络,但并不意味着它们只能在那里工作。 Code Project上提供了一个很好的控制台演示。

以下是您的代码的快速修改版本:

Imports System.ComponentModel.DataAnnotations

Public Class Form1

    Private Shadows Sub Load() Handles MyBase.Load

        Dim Test As New Test
        Test.MyInt32 = Int32.MaxValue

        MessageBox.Show(Test.MyInt32) ' Result: 1, because it got set to this in the exception handler of the property setter

    End Sub

End Class

Public Class Test

    <Range(1, 10, errormessage:="something")>
    Public Property MyInt32 As Integer
        Get
            Return Me._MyInt32
        End Get
        Set(ByVal value As Integer)
            Try
                Validator.ValidateProperty(value, New ValidationContext(Me, Nothing, Nothing) With {.MemberName = "MyInt32"})
                Me._MyInt32 = value
            Catch ex As ValidationException
                Me._MyInt32 = 1
            End Try
        End Set
    End Property

    Private _MyInt32 As Integer

End Class