2014-09-21 29 views
0

(我沒有任何問題接受VB.NET或C#解決方案)RangeAttribute不工作

我創建了這個內容寫在VB.NET一個新的空WinForms項目只測試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創建作爲答案of this question的一個描述的看點一樣,但我不喜歡這樣的解決方案,因爲我不應該依賴於第三方的lib如果.NET Framework類庫公開了一種方法來做同樣的事情(我認爲這會更好,導致DateTime類型的屬性重載等)。

回答

0

難怪它不能正常工作,因爲RangeAttribute不受WinForms的支持。您可以在名稱空間System.ComponentModel.DataAnnotations中找到的所有內容都適用於Web應用程序。

「的System.ComponentModel.DataAnnotations命名空間提供了用於定義元數據ASP.NET MVC和ASP.NET數據控件屬性類。」 - MSDN

0

您只需執行驗證。雖然System.ComponentModel.DataAnnotations通常用於Web,並不意味着它們只能在那裏工作。一個好的控制檯演示可在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 
+0

所以我們反對票正確答案? – 2015-01-07 16:09:11

+0

我投下你的答案,因爲我不相信這是正確的。我對這些課程的理解是,它們是爲網絡而構建的,但不是專門爲此編寫的,我編寫了代碼來證明它,並且包含了其他人執行相同操作的鏈接。以下是另外兩個提到它可以完成的鏈接。 http://sanjeevtechblogs.blogspot.com/2010/08/dataannotations-and-aspnet-mvc.html和http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-數據annotations.aspx。 如果您認爲我的回答錯誤,請證明。 – 2015-01-07 16:49:42

+0

那麼,你*錯*。它不受*支持,也不用於'winforms'。在[本文檔](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v = vs.110).aspx)中明確指出:'...用於定義元數據ASP.NET MVC和ASP.NET數據控件「。此外,OP明確聲明他不*依賴第三方庫(您的答案)。 – 2015-01-07 16:58:32