VB.NET调用Purchase类时遇“Purchase1未赋值即使用”错误求解决
解决“Purchase1 is used before it has been assigned a value”错误
问题根源
你只声明了Purchase类型的变量purchase1,但没有用New关键字创建类的实例——相当于只告诉程序“我要一个Purchase类型的变量”,但没给这个变量分配实际的内存空间,直接操作它的属性自然会触发未赋值使用的错误。
修复方案
1. 先实例化对象再操作属性
在使用purchase1之前,必须通过New关键字创建类的实例:
Dim purchase1 As New Purchase()
2. 修正后的完整代码
记录按钮点击事件
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click ' 实例化Purchase对象 Dim purchase1 As New Purchase() purchase1.description = txtitem.Text purchase1.price = txtprice.Text purchase1.quantity = txtquantity.Text End Sub
读取按钮点击事件
注意属性访问不需要加括号(除非你的Getter是带参数的方法,通常属性直接访问即可),同时也要先实例化对象:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' 实例化Purchase对象 Dim purchase1 As New Purchase() txtitem.Text = purchase1.description txtprice.Text = purchase1.price txtquantity.Text = purchase1.quantity End Sub
进阶优化:跨事件共享对象
如果需要在两个按钮之间共享同一个Purchase实例(比如记录数据后,点击另一个按钮读取刚才的记录),不能在每个事件里声明局部变量,要把purchase1声明为窗体级变量:
' 在窗体类的顶部声明,所有事件均可访问 Private purchase1 As Purchase Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click ' 首次使用前实例化,避免重复创建 If purchase1 Is Nothing Then purchase1 = New Purchase() End If purchase1.description = txtitem.Text purchase1.price = txtprice.Text purchase1.quantity = txtquantity.Text End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' 确保对象已实例化再访问,避免空引用错误 If purchase1 IsNot Nothing Then txtitem.Text = purchase1.description txtprice.Text = purchase1.price txtquantity.Text = purchase1.quantity End If End Sub
内容的提问来源于stack exchange,提问作者user14488435
相关产品推荐
相关产品推荐

