您可以使用TryCast跳过GetType和CType舞蹈:
Dim dtp as DateTimePicker = TryCast(ctrl, DateTimePicker) If dtp IsNot Nothing then dtp.Value = Now()
这样可以节省大约10行.
关闭Control类的扩展方法应该保持整洁:
_ Public Shared Sub ClearValue(c as Control, recursive as Boolean) Dim dtp as DateTimePicker = TryCast(c, DateTimePicker) If dtp IsNot Nothing Then dtp.Value = Now() ' Blah, Blah, Blah End Sub
编辑:如果想到忽略NullReferenceExceptions的Evil扩展方法不会让你感到畏缩:
_ Public Shared Sub ClearValue(c as CheckBox) If c IsNot Nothing Then c.Checked = False End Sub TryCast(ctrl, CheckBox).ClearValue()
这是获取Form的All GroupControls的所有控件的代码,您可以在GroupBox控件中执行某些操作
Private Sub GetControls() For Each GroupBoxCntrol As Control In Me.Controls If TypeOf GroupBoxCntrol Is GroupBox Then For Each cntrl As Control In GroupBoxCntrol.Controls 'do somethin here Next End If Next End Sub