2013-11-26 109 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

如果你不想強打字,你使用的是錯誤的平臺。我的意思是,你可以用動態的方式來完成這個工作,但是這對於邊緣情況來說確實是這樣。它會導致運行時類型查找性能下降,並且會導致您在運行時顯示的錯誤(如果使用錯誤類型的參數調用該方法)。 –

相關問題