18

我应该如何在 VB.NET中从一个Object转换为一个?Integer

当我做:

Dim intMyInteger as Integer = TryCast(MyObject, Integer)

它说:

TryCast 操作数必须是引用类型,但 Integer 是值类型。

4

4 回答 4

33

TryCast相当于 C# 的as运算符。它是一个“安全转换”运算符,如果转换失败,它不会抛出异常。相反,它返回Nothingnull在 C# 中)。问题是,您不能将Nothing( null)(引用类型)分配给(Integer值类型)。没有Integer null/之类的东西Nothing

相反,您可以使用TypeOfand Is

If TypeOf MyObject Is Integer Then
    intMyInteger = DirectCast(MyObject, Integer)
Else
    intMyInteger = 0
End If

这将测试运行时类型是否MyObjectInteger. 有关更多详细信息,请参阅有关运算符的MSDN 文档。TypeOf

你也可以这样写:

Dim myInt As Integer = If(TypeOf myObj Is Integer, DirectCast(myObj,Integer), 0)

此外,如果具有默认值(如 0)的整数不适合,您可以考虑使用Nullable(Of Integer)类型。

于 2012-10-31T04:20:19.060 回答
5

你可以使用这个:

Dim intMyInteger as Integer

Integer.TryParse(MyObject, intMyInteger)
于 2014-03-10T11:02:38.587 回答
3

使用 Directcast 并捕获 InvalidCastException

于 2012-10-31T04:21:14.123 回答
1

TryCast的等价物是CType。如果可能,两者都会进行类型转换。相比之下,DirectCast只会转换已经该类型的类型。

为了说明,您可以使用CType将 String、Short 或 Double 转换为 Integer。如果你这样做, DirectCast通常会给你一个语法/编译错误;但是,如果您尝试使用类型 Object 来绕过错误(这称为“装箱”和“拆箱”),它将在运行时引发异常。

    Dim OnePointTwo As Object = "1.2"
    Try
        Dim temp = CType(OnePointTwo, Integer)
        Console.WriteLine("CType converted to: " & temp.ToString & " (type: " & temp.GetType.ToString & ")")
    Catch ex As Exception
        Console.WriteLine("CType threw exception")
    End Try
    Try
        Dim temp = DirectCast(OnePointTwo, Integer)
        Console.WriteLine("DirectCast converted to: " & temp.ToString & " (type: " & temp.GetType.ToString & ")")
    Catch ex As Exception
        Console.WriteLine("DirectCast threw exception")
    End Try

这将输出:

    CType converted to: 1 (type: System.Int32)
    DirectCast threw exception

因此,为了最严格地遵循TryCast语义,我建议使用这样的函数:

Shared Function TryCastInteger(value As Object) As Integer?
    Try
        If IsNumeric(value) Then
            Return CType(value, Integer)
        Else
            Return Nothing
        End If
    Catch ex As Exception
        Return Nothing
    End Try
End Function

为了说明它的效果:

Shared Sub TestTryCastInteger()
    Dim temp As Integer?

    Dim OnePointTwo As Object = "1.2"
    temp = TryCastInteger(OnePointTwo)
    If temp Is Nothing Then
        Console.WriteLine("Could not convert to Integer")
    Else
        Console.WriteLine("TryCastInteger converted to: " & temp.ToString & " (type: " & temp.GetType.ToString & ")")
    End If

    Dim NotANumber As Object = "bob's your uncle"
    temp = TryCastInteger(NotANumber)
    If temp Is Nothing Then
        Console.WriteLine("Could not convert to Integer")
    Else
        Console.WriteLine("TryCastInteger converted to: " & temp.ToString & " (type: " & temp.GetType.ToString & ")")
    End If
End Sub

运行 TestTryCastInteger() 将输出:

    TryCastInteger converted to: 1 (type: System.Int32)
    Could not convert to Integer

还有诸如 null/Nothing 整数之类的东西,或任何其他静态类型,称为“可空”类型,有关更多信息,请参阅变量声明问号。但这也不能真正使它成为“参考”类型。

于 2013-08-01T16:57:52.233 回答