You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET WinForm如何跨窗体调用源窗体的UpdatePosition方法

实现方案

你已经通过TypeOf判断了控件的类型为Projectile,只需要把通用Control类型的变量强制转换为Projectile类型,即可调用自定义的UpdatePosition方法,修改后的完整代码如下:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    For Each control As Control In Controls
        If TypeOf control Is Projectile Then
            ' 将Control类型强制转换为Projectile类型后调用自定义方法
            Dim currentProjectile As Projectile = DirectCast(control, Projectile)
            currentProjectile.UpdatePosition()
        End If
    Next
End Sub

额外说明

  • 这里使用DirectCast做类型转换是安全的:前面的TypeOf判断已经确保当前遍历到的控件一定是Projectile类的实例,不会触发类型转换异常
  • 你也可以用更简洁的写法,省略单独的TypeOf判断,用TryCast尝试转换后判断结果是否为空再执行逻辑:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    For Each control As Control In Controls
        Dim currentProjectile As Projectile = TryCast(control, Projectile)
        If currentProjectile IsNot Nothing Then
            currentProjectile.UpdatePosition()
        End If
    Next
End Sub

内容的提问来源于stack exchange,提问作者schnefff boi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:54:06