gpt4 book ai didi

vb.net - 每次我离开并重新进入类(class)时,Visual Basic 都会将我的变量重置为 0

转载 作者:行者123 更新时间:2023-12-02 21:35:30 25 4
gpt4 key购买 nike

我有一个表格可以从用户那里获取财务信息,包括贷款金额、利率和期限。我应该调用一个类(class)来完成这项工作,然后将答案返回到表格中。然而,由于某种原因,每当我的程序移出类,返回表单,然后返回类时,我在类中的变量就会重置为 0。我的代码如下。任何帮助都会很棒。

这是我表单中的代码:

    'Preform calculation when button is clicked
Private Sub buttonCalc_Click(sender As Object, e As EventArgs) Handles buttonCalc.Click
Dim loanAmount As New finClass
Dim rate As New finClass
Dim term As New finClass
Dim payment As New finClass
loanAmount.getLoanAmount = textBoxMortgageAmount.Text
rate.getAnnualRate = comboBoxAnnualRate.Text.Replace("%", "")
term.getTermInYears = comboBoxTerm.SelectedItem
textBoxMonthlyPayment.Text = payment.setMonthlyPayment

End Sub

来自关联类的代码:

Public Class finClass

Private loanAmt As Decimal
Private termValue As Decimal
Private rateValue As Decimal
Public paymentValue As Decimal

Public WriteOnly Property getLoanAmount
Set(value)
If IsNumeric(value) AndAlso value > 1000 AndAlso value < 10000000 Then
Me.loanAmt = value
Else
MessageBox.Show("Mortgage amount must be a number between $1,000 and $10,000,000", "Invalid Number", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Set
End Property

Public WriteOnly Property getAnnualRate
Set(value)
rateValue = value.Replace("%", "")
If rateValue < 1 Then
rateValue *= 100
End If

End Set
End Property

Public WriteOnly Property getTermInYears
Set(value)
termValue = value
End Set
End Property

Public ReadOnly Property setMonthlyPayment
Get
Return -Pmt((rateValue / 1200), termValue * 12, Me.loanAmt)
End Get
End Property
End Class

最佳答案

我不在 VS 中工作,但看起来您正在创建该类的四个实例。我很确定这是不正确的。

Private Sub buttonCalc_Click(sender As Object, e As EventArgs) Handles buttonCalc.Click
Dim loanAmount As New finClass '## Creates NEW finClass object
Dim rate As New finClass '## Creates NEW finClass object
Dim term As New finClass '## Creates NEW finClass object
Dim payment As New finClass '## Creates NEW finClass object
loanAmount.getLoanAmount = textBoxMortgageAmount.Text
rate.getAnnualRate = comboBoxAnnualRate.Text.Replace("%", "")
term.getTermInYears = comboBoxTerm.SelectedItem
textBoxMonthlyPayment.Text = payment.setMonthlyPayment

End Sub

因此,每个对象都是 finClass 对象的不同实例。因此,每次“重新进入”类时,您实际上是在进入该类对象的不同实例,这就是为什么所有变量的 value = 0。它们尚未实例化或设置,还没有。

尝试这样做,创建一个类对象,您可以使用类模块中的方法来操作它:

Private Sub buttonCalc_Click(sender As Object, e As EventArgs) Handles buttonCalc.Click
Dim objFinClass as New finClass

objFinClass.getLoanAmount = textBoxMortgageAmount.Text
objFinClass.getAnnualRate = comboBoxAnnualRate.Text.Replace("%", "")
objFinClass.getTermInYears = comboBoxTerm.SelectedItem
textBoxMonthlyPayment.Text = objFinClass.setMonthlyPayment

End Sub

关于vb.net - 每次我离开并重新进入类(class)时,Visual Basic 都会将我的变量重置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21486964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com