我的代码类似于以下内容:
Imports System.ComponentModel.DataAnnotations
Class Person
Dim _ssn As String = ""
Public Overridable Property SSN(format As Boolean) As String
Get
If format Then
' Return formatted SSN
Else : Return _ssn
End If
End Get
Set(value As String)
_ssn = value
End Set
End Property
End Class
Class Employee
Inherits Person
<Required()>
Public Overrides Property SSN(format As Boolean) As String
Get
Return MyBase.SSN(format)
End Get
Set(value As String)
MyBase.SSN(format) = value
End Set
End Property
End Class
当我在Employee类上使用Validator.ValidateObject()时,即使SSN属性为Nothing,它也会正常验证。
为什么所需属性不起作用?
由于
答案 0 :(得分:0)
我怀疑验证不适用于索引/参数化属性,因为我不知道验证程序如何计算出format
参数传入的内容。作为一种变通方法,您可以创建一个非索引属性来放置Required
属性。
Class Employee
Inherits Person
<Required()>
Public Overloads Property SSN As String
Get
Return Me.SSN(False)
End Get
Set(value As String)
Me.SSN(False) = value
End Set
End Property
Public Overrides Property SSN(format As Boolean) As String
Get
Return MyBase.SSN(format)
End Get
Set(value As String)
MyBase.SSN(format) = value
End Set
End Property
End Class
说实话,我可能会将设计更改为具有两个属性 - 读/写SSN
属性和只读FormattedSSN
属性,这对我来说似乎更干净(但可能是& #39;只是我!)。
答案 1 :(得分:0)
看起来参数化属性不会采用必需的属性。作为一种解决方法,我使用重载来解决这个问题。
Imports System.ComponentModel.DataAnnotations
Class Person
Dim _ssn As String
Public Property SSN() As String
Get
Return _ssn
End Get
Set(ByVal value As String)
_ssn = JustNumbers(value)
End Set
End Property
Public Property SSN(format As String) As String
Get
Try
Return CInt(Me.SSN).ToString(format)
Catch ex As InvalidCastException : Return Me.SSN
End Try
End Get
Set(value As String)
SSN = value
End Set
End Property
Function IsValid() As Boolean
Return Validator.TryValidateObject(Me, New ValidationContext(Me), Nothing)
End Function
End Class
Class Employee
Inherits Person
<Required()>
Public Overloads Property SSN() As String
Get
Return MyBase.SSN
End Get
Set(value As String)
MyBase.SSN = value
End Set
End Property
End Class