我试图在Visual Basic中创建一个简单的,基于类的计算器,但是当我按下按钮(加)(乘)时,它在文本框中显示为0。
这是我的代码: 表格2:
Public Class Form2
Dim Class2 As part2Class = New part2Class()
Dim Class2b As part2ClassB = New part2ClassB()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Num1 As Integer = CType(TextBox1.Text, Integer)
Dim Num2 As Integer = CType(TextBox2.Text, Integer)
MessageBox.Show(Class2.Calculate().ToString())
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Num1 As Integer = CType(TextBox1.Text, Integer)
Dim Num2 As Integer = CType(TextBox2.Text, Integer)
MessageBox.Show(Class2b.Calculate())
End Sub
结束班级
part2Class CLASS
Public Class part2Class
Public Property Num1
Public Property Num2
Public Overridable Function Calculate() As Integer
Return Num1 + Num2
End Function
End Class
Part2ClassB
Public Class part2ClassB
Inherits part2Class
Public Overrides Function Calculate() As Integer
Return Num1 * Num2
End Function
End Class
当我在文本框中输入值并按ADD / MULIPLY时,该值将显示为0。
答案 0 :(得分:0)
您没有将值分配给类的属性。试试这个:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Num1 As Integer = CType(TextBox1.Text, Integer)
Dim Num2 As Integer = CType(TextBox2.Text, Integer)
Class2b.Num1=Num1
Class2b.Num2=Num2
MessageBox.Show(Class2b.Calculate())
End Sub
答案 1 :(得分:0)
如果CType
失败,您将使程序崩溃。我将其更改为TryParse
,该变量在第二个参数(在本例中为类的属性)中设置变量,并返回True
或False
。 AndAlso
一到达False
就停止,并前进到Else
If
部分
您需要在类中使用数据类型声明属性。查看我对Option Strict的评论。
Public Class part2Class
Public Property Num1 As Integer
Public Property Num2 As Integer
Public Overridable Function Calculate() As Integer
Return Num1 + Num2
End Function
End Class
Public Class part2ClassB
Inherits part2Class
Public Overrides Function Calculate() As Integer
Return Num1 * Num2
End Function
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Class2 As part2Class = New part2Class()
Dim message As String
If Integer.TryParse(TextBox1.Text, Class2.Num1) AndAlso Integer.TryParse(TextBox2.Text, Class2.Num2) Then
message = Class2.Calculate().ToString
Else
message = "Please enter a number in both text boxes."
End If
MessageBox.Show(message)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Class2b As part2ClassB = New part2ClassB()
Dim message As String
If Integer.TryParse(TextBox1.Text, Class2b.Num1) AndAlso Integer.TryParse(TextBox2.Text, Class2b.Num2) Then
message = Class2b.Calculate().ToString
Else
message = "Please enter a number in both text boxes."
End If
MessageBox.Show(message)
End Sub