将一个子程序的变量访问到另一个子程序-VB中

时间:2012-07-26 15:46:47

标签: vb.net

我有两个问题

  1. 我想在result

  2. 中使用Button15_ click
  3. 当我在第op = sender.Text行输入内容时,我在intellisense中看到了发件人对象的Text方法吗?

  4. 这是我的代码

    Public Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click, Button11.Click, Button12.Click, Button13.Click, Button14.Click, Button14.Click, Button16.Click
        Dim op As Char
        op = sender.Text
    
         result = Convert.ToInt32(TextBox1.Text)
    
    End Sub
    
    Public Sub Button15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button15.Click
        Select Case op
            Case "+"
                result += Convert.ToInt32(TextBox1.Text)
                TextBox1.Text = result
            Case "-"
                result -= Convert.ToInt32(TextBox1.Text)
                TextBox1.Text = result
            Case "*"
                result *= Convert.ToInt32(TextBox1.Text)
                TextBox1.Text = result
            Case "\"
                result \= Convert.ToInt32(TextBox1.Text)
                TextBox1.Text = result
    
    
        End Select
    
    
    
    
    End Sub
    

2 个答案:

答案 0 :(得分:1)

op声明为类级别:

Dim op As Char

Public Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click, Button11.Click, Button12.Click, Button13.Click, Button14.Click, Button14.Click, Button16.Click
    op = sender.Text

    result = Convert.ToInt32(TextBox1.Text)
End Sub

Public Sub Button15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button15.Click
    Select Case op
        Case "+"
            result += Convert.ToInt32(TextBox1.Text)
            TextBox1.Text = result
        Case "-"
            result -= Convert.ToInt32(TextBox1.Text)
            TextBox1.Text = result
        Case "*"
            result *= Convert.ToInt32(TextBox1.Text)
            TextBox1.Text = result
        Case "\"
            result \= Convert.ToInt32(TextBox1.Text)
            TextBox1.Text = result
    End Select
End Sub

您在IntelliSense中看不到Text的原因是senderObject,而不是TextBox,并且没有Text属性。我建议您打开Option Strict,因为它会显示几个潜在的代码错误。要获得它,请投射sender

op = DirectCast(sender, Button).Text(0)

Button15_Click中还有很多共同的逻辑。我把它重写为:

Dim rightOperand As Integer = Integer.Parse(TextBox1.Text)

Select Case op
    Case "+"c
        result += rightOperand
    Case "-"c
        result -= rightOperand
    Case "*"c
        result *= rightOperand
    Case "\"c
        result \= rightOperand
End Select

TextBox1.Text = result.ToString()

答案 1 :(得分:0)

Private op as Char

Public Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click, Button11.Click, Button12.Click, Button13.Click, Button14.Click, Button14.Click, Button16.Click 
    op = DirectCast(sender, button).Text
     result = Convert.ToInt32(TextBox1.Text) 
End Sub