我有一個這樣的模型:
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Public Class Product
Private _id As Integer
Private _name As String
Private _description As String
Private _unitPrice As Decimal
<Required(AllowEmptyStrings:=False)>
Public Property Title() As String
<Required(AllowEmptyStrings:=False)>
Public Property Id() As Integer
Get
Return _id
End Get
Set(ByVal value As Integer)
_id = value
End Set
End Property
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property Description() As String
Get
Return _description
End Get
Set(ByVal value As String)
_description = value
End Set
End Property
Public Property UnitPrice() As Decimal
Get
Return _unitPrice
End Get
Set(ByVal value As Decimal)
_unitPrice = value
End Set
End Property
End Class
還有我要驗證的代碼:
Dim results As List(Of ValidationResult) = Nothing
Dim product As New Product
If Validator.TryValidateObject(product, New ValidationContext(product), results, True) Then
MessageBox.Show(123)
Else
MessageBox.Show(results.ToString())
End If
我的問題是:
為什么
results變數總是Nothing,我怎樣才能得到錯誤訊息result并知道哪個屬性有錯誤?為什么可以
Title()驗證但Id()不能?我怎樣才能使Id()驗證?
uj5u.com熱心網友回復:
為什么
results變數總是Nothing,我怎樣才能得到錯誤訊息result并知道哪個屬性有錯誤?
當validationResults引數為 null 時,驗證會在第一個錯誤處停止,并且不會將錯誤添加到集合中。如果您希望它保存失敗驗證的集合,則必須在傳遞其參考之前初始化該集合:
Dim results As New List(Of ValidationResult)
為什么可以
Title()驗證但Id()不能?我怎樣才能使Id()驗證?
Title是一個字串,它是一個參考型別,它的默認值為 null (AKA, Nothing),而Id一個整數,它是一個默認值為 0的值RequiredAttribute型別。所以,這里沒有意義,因為屬性總是有一個值. Nullable(Of Integer)如果您希望它與以下內容一起使用,您可以將其型別更改為RequiredAttribute:
Public Property Id As Integer?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/459305.html
上一篇:從VB.NET(DataGridView)匯出到Excel時,格式化單元格值滿足條件的某些行
下一篇:.NET如何定義異步任務回呼
