在声明时为 Func 指定一个参数,在 invoke/execution 时指定另一个参数

Specify one parameter for Func at declaration time and another at invoke/execution time

根据我的研究,我没有发现任何证据表明这是可能的,所以我想知道是否有办法做到这一点或下一个最干净的解决方案?

我想避免必须将另一个参数传递给我的泛型函数以保持其整洁并提高模块化。

考虑以下通用循环函数,它在循环集合时调用谓词函数来检查特定条件:

Private Sub LoopAndApplyCondition(Of T)(ByVal collection As IDataCollection, ByVal condition As Func(Of T, String, Boolean), ByRef result As List(Of T))
  If Not collection.ActiveItems Is Nothing And collection.Count > 0 Then
    For Each record In collection
   '***
   '*** I would like to pass in the record into the predicate function here ***
   '***
        Dim meetsCondition As Boolean = condition.Invoke(CType(record, T))
        If meetsCondition Then result.Add(CType(record, T))
    Next
  End If
End Sub

这就是定义谓词函数(条件)并调用此通用循环函数的内容,它具有我想传递给谓词函数的 attributeName 字段。

Public Function AllEditableRecords(Of T)(ByVal collection As IDataObjectCollection, ByVal attributeName As String) As List(Of T)
    Dim result As New List(Of T)
    '***
    '*** I would like to pass in the attributeName field to the predicate function here ***
    '***
    Dim condition As Func(Of T, String, Boolean) = AddressOf CheckIfRecordIsEditable
    LoopAndApplyCondition(Of T)(collection, condition, result)
  Return result
End Function

这是谓词函数的签名:

Private Function CheckIfRecordIsEditable(Of T)(record As T, attributeName As String) As Boolean
  'Returns conditionResult
End Function

总而言之,我想通过 AllEditableRecords 函数和通用 [=28] 将字符串参数传递给 CheckIfRecordIsEditable =]通过LoopAndApplyCondition.

记录参数

我认为这不可能,但请证明我是错的。 我也很高兴接受 C# 中的答案,但 VB.NET 首选。

不,不能在声明委托时为委托定义参数。

然而,可能的是将 Func 及其参数封装在它自己的 class:

Public Class RecordCondition(Of T)
    Public Property CheckConditionHandler As Func(Of T, String, Boolean)
    Public Property AttributeName As String
End Class

AllEditableRecords 中创建 RecordCondition:

Public Function AllEditableRecords(Of T)(ByVal collection As IDataObjectCollection, ByVal attributeName As String) As List(Of T)
    Dim result As New List(Of T)

    Dim recordCondition As New RecordCondition(Of T) With {.CheckConditionHandler = AddressOf CheckIfRecordIsEditable, .AttributeName=attributeName}
    LoopAndApplyCondition(Of T)(collection, recordCondition, result)
    Return result
End Function

LoopAndApplyCondition 中调用 CheckConditionHandler:

Private Sub LoopAndApplyCondition(Of T)(ByVal collection As IDataCollection, ByVal condition As RecordCondition(Of T), ByRef result As List(Of T))
    If Not collection.ActiveItems Is Nothing And collection.Count > 0 Then
        For Each record In collection
            Dim meetsCondition As Boolean = condition.CheckConditionHandler(record, condition.AttributeName) 
            If meetsCondition Then result.Add(CType(record, T))
        Next
    End If
End Sub

CheckIfRecordIsEditable 不变。