为什么这段代码不会向数组“数字”添加元素?
Dim numbers() As Double
Dim counter As Integer
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Const BASE As Double = 200 'base pay
Const COMM As Double = 1.09 'commission rate
Dim gross As Double = txtSalesAmount.Text 'user input (gross sales)
Dim pay As Double = BASE + (gross * COMM) 'calculates total pay
numbers(counter) = pay
counter += 1
txtSalesAmount.Text = ""
我得到的只是可怕的例外:
An unhandled exception of type 'System.NullReferenceException' occurred in Salary_Summary.exe
Additional information: Object reference not set to an instance of an object.
你可以告诉我,我是一个完整的新手......对不起,如果这是陈腐的话。
答案 0 :(得分:1)
你没有初始化数组。此外,阵列的大小是固定的。我建议使用List(Of Double)
。
答案 1 :(得分:1)
Dim gross As Double = txtSalesAmount.Text
错误,因为您需要将文字转换为数字,我建议将Decimal
与货币一起使用。numbers()
永远不会初始化为任何大小。 .NET
中的数组具有固定大小,需要针对大小进行初始化。示例Dim numbers as Double() = New Double(100) { }
Array.Resize()
函数调整数组大小以适应更多元素List(Of )
,但它会在内部处理所有簿记和调整大小。Nothing
的引用。