gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:38:05 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 对象的不同实例。因此,每次您“重新进入”该类时,您实际上是在进入该类对象的不同实例,这就是为什么所有变量的值都为 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 - 每次我离开并重新进入类时,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