我想创建一个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.
我错过了什么?
答案 0 :(得分: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)
我没有错误。
答案 1 :(得分:0)
这是一个错误的错误消息。我在界面中的签名与实现中的签名不同。一旦我修复了签名,错误就消失了。