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

VB.Net如何向子程序传递属性/方法引用以更新进度条消息?

实现支持动态属性指定的通用进度条For Each子程序

要实现你想要的动态指定对象属性作为进度条消息的功能,不用自定义Identifier类型,直接用.NET内置的Func(Of T, String)委托就能搞定,这是最简洁且符合.NET设计习惯的方案。

修改后的通用For Each子程序

Sub FE(Of T)(c As IEnumerable(Of T), body As Action(Of T), Optional pb As ProgBar = Nothing, Optional itemFormatter As Func(Of T, String) = Nothing)
    Dim itemList = c.ToList()
    Dim totalItems = itemList.Count
    If pb IsNot Nothing Then pb.Start(totalItems)
    
    For i = 0 To totalItems - 1
        Dim item = itemList(i)
        ' 检测取消信号
        If pb IsNot Nothing AndAlso pb.Cancel Then Exit For
        
        ' 执行传入的业务逻辑
        body(item)
        
        ' 更新进度条消息
        If pb IsNot Nothing Then
            Dim progressMessage As String
            If itemFormatter IsNot Nothing Then
                ' 使用自定义的对象格式化逻辑
                progressMessage = itemFormatter(item)
            Else
                ' 默认进度消息格式
                progressMessage = $"Item [{i + 1}/{totalItems}]"
            End If
            pb.Update(progressMessage)
        End If
    Next
    
    If pb IsNot Nothing Then pb.Close()
End Sub

调用示例

你可以直接通过lambda表达式指定要提取的对象属性或自定义消息逻辑,完全符合你想要的调用风格:

' 示例1:提取Sketch对象的Name属性作为进度消息
FE(Of Sketch)(sketchCollection, 
    Sub(x As Sketch)
        x.Visible = Not x.Visible
    End Sub,
    New ProgBar("切换草图可见性"),
    Function(x) x.Name
)

' 示例2:组合多个属性生成复杂消息
FE(Of Sketch)(sketchCollection,
    Sub(x) x.Visible = Not x.Visible,
    New ProgBar("批量处理草图"),
    Function(x) $"正在处理:{x.Name} (ID: {x.Id})"
)

' 示例3:不指定格式化逻辑,使用默认消息
FE(Of Sketch)(sketchCollection,
    Sub(x) x.Visible = Not x.Visible,
    New ProgBar("批量操作")
)

关键说明

  • 灵活性:Func(Of T, String)支持任意从T类型到字符串的转换逻辑,不仅能提取属性,还能调用对象的方法(比如Function(x) x.GetDisplayName())、添加自定义计算,扩展性远超自定义标识符类型。
  • 性能优化:提前将集合转为List并通过索引遍历,避免了原代码中IndexOf带来的性能损耗,尤其适合大集合场景。
  • 错误检查:后续可以在调用itemFormatter(item)时添加Try-Catch块,处理属性不存在或调用失败的情况,确保程序稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:37:03