如何防止缩小和后期绑定?

时间:2016-10-28 14:44:24

标签: vb.net

这可能是一个愚蠢的问题,但我第一次启用了Option Strict,我不确定这里的最佳方法是什么。

我有一堆动态创建的PictureBox控件,我在创建它们时会添加事件处理程序来处理它们的绘制事件。在paint事件中,我需要访问PictureBox的ClientRectangle。请注意,我已将发件人作为对象更改为发件人作为PictureBox

Public Sub Example(sender As PictureBox, e As PaintEventArgs)
    AlreadyExistingRectangle = sender.ClientRectangle
    AlreadyExistingRectangle.Inflate(-2, -2)
    ' Draw stuff in AlreadyExistingRectangle
End Sub

我出于各种原因需要AlreadyExistingRectangle(虽然我怀疑有更好的解决方案)。我使用发件人作为PictureBox 的原因是因为我的绘制事件有点慢,我认为它可能加快速度,因为sender.ClientRectangle会导致后期绑定。但现在,缩小发生,因为委托子使用发送者作为对象

那么,有一个简单的解决方案,还是应该允许后期绑定或缩小?如果是这样,哪个更快?

1 个答案:

答案 0 :(得分:1)

我认为如果您在Paint事件处理程序中创建了一个变量,并将sender强制转换为PictureBox,那么它最好。然后,您可以将整个事件包装在scala.collection.immutable.List中,以捕获sender 不是 PictureBoxTry/Catch block抛出的强制转换异常。

Try
    Dim senderPictureBox As PictureBox = DirectCast(sender, PictureBox)
    'Do your stuff...
Catch ex As InvalidCastException
    'Either do something here or just ignore the error.
End Try

或者,因为抛出异常对你已经很费用,正如你所说的那样,代码速度慢,你可以使用DirectCast而不是抛出异常,如果强制转换失败则只返回Nothing(这是性能要快得多。

Dim senderPictureBox As PictureBox = TryCast(sender, PictureBox)

If senderPictureBox IsNot Nothing Then
    'Do your stuff...
End If
相关问题