I have the following subroutine:
Private Sub MySub(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlAdded
Try
AddHandler CType(e.Control, MyDerivedControlType).selectionC开发者_C百科hanged, AddressOf MyEventHander
Catch ' This just protects against other types of control being added to the group box
End Try
End Sub
The intention is that an event handler is set for any control added to the form, but only if it's a certain kind of control — determined by what its most-derived type is.
Putting overarching design concerns aside for the time being, although this subroutine functions properly, when running the debugger the constant exceptions keep leaving messages in my "Immediate Window". It's annoying, and presumably throwing exceptions only to immediately re-catch them is wasteful.
Can I figure out whether the CType
will succeed before attempting it? And thus avoid this exception-as-logic-flow?
You can make use of TryCast.
Private Sub MySub(ByVal sender As Object, ByVal e As ControlEventArgs) Handles Me.ControlAdded
Dim ctl = TryCast(e.Control, MyDerivedControlType)
If (ctl IsNot Nothing) Then
AddHandler ctl.selectionChanged, AddressOf MyEventHander
End If
End Sub
TryCast
will return Nothing
if the cast isn't successful or it will return the object casted to the specified type. I believe in C# this "try cast" would look like var ctl = e.Control as MyDerivedControlType;
.
I don't know what the VB equivalent is, but in C# you can do this:
if (e.Control is MyDerivedControl)
{
MyDerivedControl ctrl = (MyDerivedControl)e.Control;
}
EDIT: Here's the code in VB.NET
If TypeOf ctrl Is MyDerivedControl Then
Dim derivedCtrl As MyDerivedControl = DirectCast(ctrl, MyDerivedControl)
End If
Before your current line, you could use TryCast instead of the CType. Use the result when adding the event if the result is not nothing.
精彩评论