2

我想创建一个 GetAllContacts 方法,它采用 Func(Of Contact, TKey) 类型的排序参数,它与 IEnumerable(Of Contact) 的 OrderBy 方法采用的类型相同。这是我的代码:

    Public Function GetAllContacts(Of TKey)(ByVal sort As Func(Of Contact, TKey), ByVal sortDirection As SortDirection) As IEnumerable(Of Contact) Implements IContactRepository.GetAllContacts
        Select Case sortDirection
            Case sortDirection.Ascending
                Return ContactList.OrderBy(sort)
            Case sortDirection.Descending
                Return ContactList.OrderByDescending(sort)
        End Select
    End Function

当我调用 GetAllContacts(Func(c) c.ContactID, SortDirection.Ascending) 时,出现错误:

"Value of type 'System.Func(Of Contact, String)' cannot be converted to 'Integer'." on the first parameter

"Too many arguments to extension method 'Public Function ElementAtOrDefault(index As Integer) As Contact' defined in 'System.Linq.Enumerable'." on the second parameter.

我错过了什么?

4

2 回答 2

1

我试过这个(净4.0):

Public Function tst(a As String) As Integer
        Return a.Length
    End Function

    Public Function GetAllContacts(Of TKey)(ByVal sort As Func(Of String, TKey), ByVal sortDirection As DirectoryServices.SortDirection) As IEnumerable(Of String)
        Return {"a"}
    End Function

和这个:

GetAllContacts(AddressOf tst, DirectoryServices.SortDirection.Ascending)
GetAllContacts(Function(a As String) As Integer
                       Return a.Length
                   End Function, DirectoryServices.SortDirection.Ascending)
GetAllContacts(Function(a) a.Length, DirectoryServices.SortDirection.Ascending)

我没有错误。

于 2012-05-28T13:58:28.383 回答
0

这是错误消息的情况。我在接口中的签名与在实现中的签名不同。一旦我修复了签名,错误就消失了。

于 2012-05-29T11:11:58.517 回答