从另一个函数vb.net调用一个控制方法



我想知道是否可以使用与另一个函数的控件关联的方法。例如

Sub myCheckBox(sender As Object, e As EventArgs) Handles myCheckBox.CheckedChanged
'''Code I want to run from other function
End Sub
Function MyOtherFunction(x as double, y as double) as double
'''Call myCheckBox method
End function

假设WinForms:

Dim cbs = Me.Controls.OfType(Of Checkbox)().Where(Function(cb) cb.Checked).ToList()
For Each cb In cbs
  'run code for each checkbox that is checked
Next

通常明智的做法是将事件中的代码限制为处理与用户相关的事情。您可以将通用代码放在subs中,并从事件、其他方法(subs)和其他函数调用它们:

  Sub myCheckBox(sender As Object, e As EventArgs) Handles myCheckBox.CheckedChanged
     ' user / click related code
     ' ...
     CommonReusableCodeSub(sender As object)
  End Sub
  Function MyOtherFunction(x as double, y as double) as double
     ' do some special stuff, maybe even just to prep
     ' for the call to a common sub
     CommonReusableCodeSub(Nothing)
  End function
  Sub CommonReusableCodeSub(chk as CheckBox) ' can also be a function
      ' do stuff common to both above situations
      ' note how to detect what is going on:
      If chk Is Nothing then
         ' was called from code, not event
         ' do whatever
         Exit Sub      ' probably
      End If
      Select Case chk.Name     ' or maybe chk.Tag
          chk.thisOption
            ' do whatever
          chk.thatOption
            ' do whatever
          ' etc...
       End Select
  End Sub

这可以防止应用程序逻辑(业务/网络等)毫无希望地混合在一起,甚至依赖于UI层和当前布局。注意:有些控件实现了一种调用事件代码的方式:例如,按钮和单选按钮有一个btn.PerformClick,而复选框则没有这种运气。

最新更新