【问题标题】:Using Action(Of T...) over a custom delegate syntax for readability在自定义委托语法上使用 Action(Of T...) 以提高可读性
【发布时间】:2011-01-07 14:29:49
【问题描述】:

自 .net 4.0 以来,使用以下语法的新礼仪是:

Private Sub Main()
    MyMethod(AddressOf AnAction)
End Sub

Private Sub MyMethod(ByVal toDo As Action(Of String, Integer, Boolean))
    toDo.Invoke("Tom", 1, True)
End Sub

Private Sub AnAction(ByVal p1 As String, ByVal p2 As Integer, ByVal p3 As Boolean)
End Sub

相对于:

Private Delegate Sub MyActionDlg(ByVal p1 As String, ByVal p2 As Integer, ByVal p3 As Boolean)

Private Sub Main()
    MyMethod(AddressOf AnAction)
End Sub

Private Sub MyMethod(ByVal toDo As MyActionDlg)
    toDo.Invoke("Tom", 1, True)
End Sub

Private Sub AnAction(ByVal p1 As String, ByVal p2 As Integer, ByVal p3 As Boolean)
End Sub

Tuples/Func 也是如此。写的很好,但有些地方感觉有点草率。为什么有人想要 Tuple(Of T, T2, T3, T4) 而不是一个好的类类型?我的实际代码有这些嵌套,因此它通过一系列方法传递 Action。

对不起,对于 VB 示例,AddressOf 只是 VB 表达new Action(AnAction) 的方式。另外我只是把它写到浏览器中,所以它也可能无法编译。

人们对阅读和使用这些编译器通用操作而不是根据解决方案中的确切要求而制作的适当特殊实体有何感受?

【问题讨论】:

    标签: .net vb.net compiler-construction action


    【解决方案1】:

    新的 FuncAction 委托更适合 LINQ 方法中的 sed 等简单委托。

    如果使用Funcs 或Actions 会导致类型名不可读,那么您当然应该定义自己的委托。

    一般来说,您应该选择代码可读性最强的设计。

    【讨论】:

    • 我明白了,在这种情况下,为 LINQ 命令保留 Func 和 Action 似乎是合适的。适当的应用程序控制委托更容易阅读和定期使用。感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 2017-07-02
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多