在 VB.NET 中将字符串转换为整数的 TryCast

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36335196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:47:19  来源:igfitidea点击:

TryCast for string to integer in VB.NET

vb.net

提问by James Yeoman

I do not understand at all how to use TryCast in my code, but it is something I need to use for validating user input. I have done various searches and looked at various questions on here, but no one seems to actually say how to use it, and the MSDN website doesn't seem to help at all.

我完全不明白如何在我的代码中使用 TryCast,但我需要使用它来验证用户输入。我已经在这里进行了各种搜索并查看了各种问题,但似乎没有人真正说明如何使用它,而且 MSDN 网站似乎根本没有帮助。

    Function ValidateInput(Var_In As String) As Integer

        If TryCast(Var_In, Integer) = Nothing Then

            Return vbNull
        Else
            Return Var_In
        End If
    End Function

The error says that

错误说

The operand must be of reference type but Integer is of value type

操作数必须是引用类型,但整数是值类型

What is the explanation of what I have done wrong?

我做错了什么的解释是什么?

TryParse doesn't accept more than 10 digits so for example, an input of "12345678901" won't be accepted. How do I fix this?

TryParse 不接受超过 10 位的数字,例如,“12345678901”的输入将不被接受。我该如何解决?

回答by Martin Verjans

Let's try to understand the differences between TryCast, Convert and TryParse.

让我们尝试了解TryCast、Convert 和 TryParse之间的区别。

TryCast

试播

This function will attempt to convert one object into another type, as long as it is a reference type.

此函数将尝试将一个对象转换为另一种类型,只要它是引用类型。

Dim MyNewObject = TryCast(MyObject, MyReferenceClass)
If IsNothing(MyNewObject) Then
    MessageBox.Show("Impossible to cast")
End If

Since Integer is a value type, it will not work, so we have to figure something out...

由于Integer是值类型,所以行不通,所以我们得想办法……

Convert

转变

Convert Class on MSDN

在 MSDN 上转换类

From MSDN:

来自 MSDN:

Converts a base data type to another base data type.

将基本数据类型转换为另一种基本数据类型。

So we can try:

所以我们可以试试:

Dim myInt = Convert.ToInt32(MyObject)

The problem is that it will generate an exception InvalidCastExceptionif it's impossible to do the conversion.

问题在于,InvalidCastException如果无法进行转换,则会产生异常。

TryParse

尝试解析

This function is trying to convert a Stringinto something you want. And it will not generate an exception:

这个函数试图将 a 转换String成你想要的东西。它不会产生异常:

Dim myInt As Integer = 0
If Not Integer.TryParse(MyString, myInt) Then
    MessageBox.show("This is not an integer")
End If

Limitation

局限性

Converting a String into a Integer can sometimes be tricky... If the String represents a number that is greater or lesser than Integer.MaxValueand Integer.MinValue, you will end up with no conversion...

将字符串转换为整数有时会很棘手......如果字符串表示一个大于或小于Integer.MaxValueand 的数字Integer.MinValue,你最终将无法进行转换......

So you can go with a Double:

所以你可以使用Double

Double.TryParse(MyString, MyDouble)

Or personally, if you know that it will be a number, use Decimal:

或者就个人而言,如果您知道它将是一个数字,请使用十进制:

Decimal.TryParse(MyString, MyDecimal)

See Decimals on MSDN

请参阅 MSDN 上的小数

Decimal still has a Max and Min value, according to MSDN:

根据 MSDN,十进制仍然有最大值和最小值:

The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors.

Decimal 值类型表示从正 79,228,162,514,264,337,593,543,950,335 到负 79,228,162,514,264,337,593,543,950,335 的十进制数。Decimal 值类型适用于需要大量有效整数和小数位且没有舍入错误的财务计算。

Convert.ChangeType

转换.ChangeType

This oneis also interesting, but is a bit weird...

这个也很有意思,就是有点奇怪……

回答by David W

You are attempting to perform TryCastagainst an Integer, which is a value type. TryCastworks only on referencetypes, such as (but not limited to) a Class, Object, or Stringtype.

您正在尝试TryCast对 Integer执行,这是一个值类型TryCast只对参考类型,诸如(但不限于)一个ClassObjectString类型。

If you are trying to convert the input parameter to an Integer, you might try one of the methods in the Convertclass, such as Convert.ToInt32()or Integer.TryParse.

如果您尝试将输入参数转换为整数,您可以尝试Convert类中的方法之一,例如Convert.ToInt32()Integer.TryParse

回答by Dr. Aaron Dishno

Instead of TryCast, use TryParse:

使用 TryParse 代替 TryCast:

Function ValidateInput(Var_In As String) As Integer
    Dim iNum As Integer
    If (Integer.TryParse(Var_In, iNum)) Then
        Return iNum
    Else
        Return vbNull
    End If
End Function

回答by Claudius

Much better is to use TryParse:

更好的是使用 TryParse:

Function ValidateInput(Var_In As String) As Integer   
    Dim num as Integer
    If Not Integer.TryParse(Var_In, num) Then
        Return vbNull
    Else
        Return num
    End If
End Function