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
相关产品推荐
相关产品推荐

