为什么我不能在这个参数上使用方法?

时间:2013-11-26 18:34:29

标签: vb.net

我正在尝试在此重载方法中对集合使用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

1 个答案:

答案 0 :(得分:4)

编译器无法保证您的泛型类型T将具有名为“id”的属性。因此,c.id来电中的Where()表达式不合法,因为该属性可能不存在。

要解决此问题,您需要您的泛型方法约束到某个接口,该接口承诺id整数属性可用,让方法请求一个将投影您的类型的函数Tid,或使用其他一些技巧,让编译器更多地了解你的类型或类型到id整数的投影。