2013-11-26 64 views
1

我试图使用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 

回答

4

编译器有没有办法保证你的泛型类型T将有一个名为“id”的属性。因此,Where()调用中的c.id表达式不合法,因为该属性可能不存在。

要解决这个问题,就需要约束您的通用方法的一些接口,承诺的id整数属性将可用,有方法要求将项目的类型Tid功能,或使用一些其他技巧将允许编译器更多地了解您的类型或类型到id整数的投影。

+0

有没有不使用强打字的解决方案?我试过了,当我删除键入的参数时,我得到一个运行时异常,声称我的集合没有'Where'方法。 –

+0

如果你不想强打字,你使用的是错误的平台。我的意思是,你可以用动态的方式来完成这个工作,但是这对于边缘情况来说确实是这样。它会导致运行时类型查找性能下降,并且会导致您在运行时显示的错误(如果使用错误类型的参数调用该方法)。 –

相关问题