如何在VB.NET中比较变量数据类型?我的尝试为何无效?
问题原因及解决方法
原代码无效的原因
你写的代码里,firstName被声明为String类型,而且Console.ReadLine()的返回值永远是字符串——哪怕用户输入数字、符号,它们都是以字符串形式存储的,所以firstName的类型始终是String。这就导致firstName IsNot GetType(String)这个条件永远为False,错误提示自然不会触发。
正确的判断思路
你要做的不是判断变量的类型,而是判断变量的内容是否符合预期格式。比如要检测输入是不是整数(名字不该是纯数字),可以用类型转换的TryParse方法;如果要限制输入只能是字母,也可以用正则表达式。
示例代码1:检测输入是否为整数
Dim firstName As String Dim tempInteger As Integer Console.Write("Please enter your first name: ") firstName = Console.ReadLine() ' 尝试将输入转换为整数,转换成功则说明输入是纯数字,不符合要求 If Integer.TryParse(firstName, tempInteger) Then Console.WriteLine("Error: Name cannot be a number, please try again.") Else Console.WriteLine($"Hello, {firstName}!") End If
示例代码2:严格限制输入为字母(含空格)
如果需要更严格的校验,比如名字只能包含字母和空格(支持中间名),可以用正则表达式:
Imports System.Text.RegularExpressions Dim firstName As String Console.Write("Please enter your first name: ") firstName = Console.ReadLine() ' 匹配仅含字母和空格的字符串 If Not Regex.IsMatch(firstName, "^[a-zA-Z\s]+$") Then Console.WriteLine("Error: Name should only contain letters and spaces, please try again.") Else Console.WriteLine($"Hello, {firstName}!") End If
内容的提问来源于stack exchange,提问作者Huzaifa
相关产品推荐
相关产品推荐

