我正在尝试在此重载方法中对集合使用Where
方法:
Private Function getIndexOfObjectById(Of T)(ByVal collection As SortableBindingList(Of T), ByVal id As Integer)
Dim cy = collection.Where(Function(c) c.id = id).FirstOrDefault()
Return collection.IndexOf(cy)
End Function
但是我得到一个错误,即使我知道该方法存在:
Error 1 Overload resolution failed because no accessible 'Where' can be called with these arguments:
Extension method 'Public Function Where(predicate As System.Func(Of T, Integer, Boolean)) As System.Collections.Generic.IEnumerable(Of T)' defined in 'System.Linq.Enumerable': Nested function does not have a signature that is compatible with delegate 'System.Func(Of T, Integer, Boolean)'.
Extension method 'Public Function Where(predicate As System.Func(Of T, Boolean)) As System.Collections.Generic.IEnumerable(Of T)' defined in 'System.Linq.Enumerable': 'id' is not a member of 'T'. \\... 5693 18
答案 0 :(得分:4)
编译器无法保证您的泛型类型T
将具有名为“id”的属性。因此,c.id
来电中的Where()
表达式不合法,因为该属性可能不存在。
要解决此问题,您需要将您的泛型方法约束到某个接口,该接口承诺id
整数属性可用,让方法请求一个将投影您的类型的函数T
到id
,或使用其他一些技巧,让编译器更多地了解你的类型或类型到id整数的投影。