变量'X'在被赋值之前使用?

时间:2014-01-08 18:36:35

标签: vb.net

我已经搜遍了它。但对此没有任何解决方案。 错误: - 变量'pri'在被赋值之前使用。在运行时可能会导致空引用异常 这种类型是显示

Public Function writepacket(ByRef dataa As String, ByRef heading As String) As Object
        Dim logpath As Object
        logpath = "C:\ZASHIT.txt"
        Dim prit, x, ppp, pri As Object
        FileClose(1)
        If dataa = "JH" Then
            FileOpen(1, logpath, OpenMode.Append)
            PrintLine(1, " ")
            PrintLine(1, "/////////////////" & heading & "//////////////////")
            PrintLine(1, " ")
            FileClose(1)
        Else
            FileOpen(1, logpath, OpenMode.Append)
            PrintLine(1, heading)
            PrintLine(1, dataa & "              " & TimeOfDay)
            x = 1
            Do Until x = Len(dataa) + 1
                pri = **pri** & Asc(Mid(dataa, x, 1)) & " "
                ppp = Hex(Asc(Mid(dataa, x, 1)))
                If Len(ppp) = 1 Then ppp = "0" & ppp
                prit = **prit** & ppp & " "
                x = x + 1
            Loop
            PrintLine(1, pri & "    ---    " & TimeOfDay)
            PrintLine(1, prit & "    ---    " & TimeOfDay)
            PrintLine(1, " ")
            FileClose(1)
        End If
**End Function**

2 个答案:

答案 0 :(得分:3)

VB.NET不是旧的Visual Basic。习惯于对类型保持纪律 - 对所有变量使用Object是非常糟糕的做法。使用String表示字符串,使用Integer表示整数等。

Public Sub writepacket(ByRef dataa As String, ByRef heading As String)
'Change to Sub - you're not writing a function - it's not returning anything
    Dim logpath As String         'Dim as String!
    logpath = "C:\ZASHIT.txt"
    Dim prit, ppp, pri As String  'Dim as String!
    Dim x As Integer              'Dim as Integer!
    FileClose(1)
    If dataa = "JH" Then
        FileOpen(1, logpath, OpenMode.Append)
        PrintLine(1, " ")
        PrintLine(1, "/////////////////" & heading & "//////////////////")
        PrintLine(1, " ")
        FileClose(1)
    Else
        FileOpen(1, logpath, OpenMode.Append)
        PrintLine(1, heading)
        PrintLine(1, dataa & "              " & TimeOfDay)
        x = 1
        pri = ""      'Initialize your string variables!
        prit = ""     'Initialize your string variables!
        Do Until x = dataa.Length + 1
        ' prefer string.Length property instead of Len()
            pri = pri & Asc(Mid(dataa, x, 1)).ToString() & " "
            ' use explicit conversions! -->  .ToString() 
            ppp = Hex(Asc(Mid(dataa, x, 1)))
            If ppp.Length = 1 Then ppp = "0" & ppp
            ' prefer string.Length property instead of Len()
            prit = prit & ppp & " "
            x = x + 1
        Loop
        PrintLine(1, pri & "    ---    " & TimeOfDay)
        PrintLine(1, prit & "    ---    " & TimeOfDay)
        PrintLine(1, " ")
        FileClose(1)
    End If
End Sub

答案 1 :(得分:1)

在Do直到你指定Pri为Pri +“......” 与每个对象一样,你必须在使用之前分配内存并分配pri。