从进行其他函数/逻辑检查的 Textchanged 事件调用时,函数将无法正确运行

问题描述 投票:0回答:1

我有一个从 TextChanged 事件中调用的函数(如下),当该函数被单独调用时,它会按预期工作,但是当我将文本长度检查引入到同一个 Textchanged 事件子中时,VerifyContent 函数始终返回 false。

Public Function VerifyContent(input As String, VerificationType As Integer) As Boolean
    VerifyContent = False
    If VerificationType = 1 Then ' Type 1 is to check whether the value is a whole integer value
        Dim intValue As Integer
        If Integer.TryParse(input, intValue) Then ' Explicit conversion using TryParse
            VerifyContent = True
        End If
    End If
End Function

Private Sub Tariff_TextChanged(sender As Object, e As EventArgs) Handles Tariff.TextChanged

        If Me.Tariff.Text.Length <> 10 Then ' Use Length property and strict comparison
            Console.WriteLine("Length check failed.")
            Exit Sub
        End If

        If VerifyContent(Me.Tariff.Text, 1) Then
            Console.WriteLine("Content verification passed.")
            MsgBox("This works a treat!")
        Else
            Console.WriteLine("Content verification failed.")
        End If
End Sub
vb.net winforms
1个回答
0
投票

这个问题几乎肯定与您的长度检查无关,而与实际数据有关。您正在寻找 10 位数字,但可能的 10 位数字中只有一小部分可以解析为

Integer
Integer.MaxValue
2147483647
,因此任何大于该值的输入都无法转换为
Integer
。如果您希望能够使用此类值,则需要使用
Long
而不是
Integer

也就是说,如果您实际上没有使用生成的数字,那么可能根本不需要生成它。如果您关心的是输入都是数字,那么您可以检查这一点而无需转换任何内容:

If input.All(Function(ch) Char.IsDigit(ch)) Then
    'All characters in input are digits.
End If

A

String
是一个
IEnumerable(Of Char)
,因此您可以在其上使用 LINQ 来查询它包含的字符。当且仅当列表中的所有项目满足指定条件时,
All
扩展方法才返回
True

我还没有在 VB 中测试过这个,但是根据 C# 中的工作原理,我非常确定这个语法也能工作:

If input.All(AddressOf Char.IsDigit) Then
    'All characters in input are digits.
End If

All
这样的方法将委托作为参数,因此您可以使用 lambda 表达式或任何其他适当类型的委托。当调用
IEnumerable(Of T)
时,委托必须有一个
T
类型的参数并返回
Boolean

© www.soinside.com 2019 - 2024. All rights reserved.