You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

StringLengthAttribute未强制长度:VB.NET中如何让其触发异常?

解决VB.NET中StringLength特性不自动验证的问题

StringLength特性属于System.ComponentModel.DataAnnotations下的元数据特性,.NET框架不会自动在属性赋值时触发它的验证逻辑,所以需要手动实现验证逻辑,才能让超长字符串赋值时抛出异常。

实现方法:在属性setter中手动触发验证

修改你的类,在属性的set访问器里调用Validator.ValidateProperty方法,利用特性定义的规则验证输入值,不符合规则时会自动抛出ValidationException:

Imports System.ComponentModel.DataAnnotations

Module Module1
    Class C1
        Private _bufferId As String

        <StringLength(3)>
        Public Property BufferId As String
            Get
                Return _bufferId
            End Get
            Set(value As String)
                ' 创建验证上下文,指定当前实例和要验证的属性名
                Dim validationContext As New ValidationContext(Me) With {
                    .MemberName = NameOf(BufferId)
                }
                ' 触发属性验证,不符合规则则抛出ValidationException
                Validator.ValidateProperty(value, validationContext)
                _bufferId = value
            End Set
        End Property
    End Class

    Sub Main()
        Dim c1 = New C1()
        Try
            c1.BufferId = "abcd"
            Console.WriteLine($"c1.BufferId={c1.BufferId}")
        Catch ex As ValidationException
            Console.WriteLine($"验证失败:{ex.Message}")
        End Try
        Console.ReadKey()
    End Sub
End Module

补充说明

  • 如果需要强制字符串非空,可同时添加<Required>特性,这样空字符串也会触发验证异常。
  • Validator.ValidateProperty会严格遵循StringLength的规则:允许字符串长度小于等于指定值,空字符串默认合法(除非搭配Required)。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 11:35:08