vb.net 警告 BC42104 - 在赋值之前使用了变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17515789/
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
warning BC42104 - Variable used before assigned a value
提问by Kre?imir ?ulina
I'm trying to download a string from a file and I'm getting the following warning(s)
我正在尝试从文件下载字符串,但收到以下警告
warning BC42104: Variable 'inst' is used before it has been assigned a value. A null reference exception could result at runtime.
警告 BC42104:变量“inst”在被赋值之前就被使用了。在运行时可能会导致空引用异常。
This is my code
这是我的代码
Dim inst As WebClient
Dim inst2 As WebClient
Dim inst3 As WebClient
Try
MsgBox("started")
ver = inst.DownloadString("http://www.xxxxxxxxx.com/update/version.xml")
loc = inst2.DownloadString("http://www.xxxxxxxxx.com/update/loc.xml")
desc = inst3.DownloadString("http://www.xxxxxxxxx.com/update/description.xml")
If (String.Compare(ver, String.Format(Nothing, My.Application.Info.Version.Major.ToString) + "." + String.Format(Nothing, My.Application.Info.Version.Minor.ToString)) = False) Then
updreq = True
End If
Catch ex As Exception
MessageBox.Show("Error occured: " + ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
回答by Guffa
The code would certainly cause a null reference exception. You have declared variables to hold the WebClientobject, but you haven't created any actual WebClientinstances.
该代码肯定会导致空引用异常。您已经声明了保存WebClient对象的变量,但您还没有创建任何实际WebClient实例。
Create instances of the WebClientclass for the variables:
WebClient为变量创建类的实例:
Dim inst As WebClient = New WebClient()
or the shorthand:
或简写:
Dim inst As New WebClient()
回答by Bobi
I had a similar situation and I did the same as above but for a TabPage:
我遇到了类似的情况,我做了与上面相同的操作,但对于 TabPage:
Private Sub btnAddTab_Click(sender As Object, e As EventArgs) Handles btnAddTab.Click
Dim number As Integer = TabControl1.TabPages.Count
Dim tab As TabPage = New TabPage()
tab.Text = "TabPage" & number + 1
TabControl1.TabPages.Add(tab)
tab.BackColor = Color.DarkGreen
End Sub

