Result Validator 总是什么都没有,我如何通过带有 prop 的消息获取它?

Result Validator is always nothing, how do I get it with message with prop?

我有一个这样的模型:

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

我的问题是:

  1. 为什么 results 变量总是 Nothing 以及如何从 result 获取错误消息并知道哪个 属性 有错误?

  2. 为什么Title()可以验证,而Id()不能?我怎样才能使 Id() 有效?

Why is the results variable always Nothing and how can I get the error message from result and know which property has an error?

validationResults 参数为 null 时,验证会在第一个错误处停止,并且不会将任何错误添加到集合中。如果你想让它保存失败验证的集合,你必须在传递它的引用之前初始化集合:

Dim results As New List(Of ValidationResult)

Why can Title() be validated but Id() cannot? And how can I make Id() validated?

Title 是一个字符串,它是一个 reference 类型,其默认值为空(又名,Nothing),而 Id是一个整数,它是一个 value 类型,其默认值为 0。因此,RequiredAttribute 在这里没有意义,因为 属性 将始终有一个值。如果您希望它与 RequiredAttribute:

一起使用,您可以将其类型更改为 Nullable(Of Integer)
Public Property Id As Integer?