如何在下面的示例中使用IList(Of T).Max函數?如何使用VB.NET IList(Of T).Max
Dim myList as IList(Of Integer)
For x = 1 to 10
myList.add(x)
Next
'Error: 'Max' is not a member of 'System.Collections.Generic.IList(Of Integer)'
MsgBox(myList.Max())
如何在下面的示例中使用IList(Of T).Max函數?如何使用VB.NET IList(Of T).Max
Dim myList as IList(Of Integer)
For x = 1 to 10
myList.add(x)
Next
'Error: 'Max' is not a member of 'System.Collections.Generic.IList(Of Integer)'
MsgBox(myList.Max())
當你調用myList.add時,你的代碼會拋出System.NullReferenceException,因爲它沒有被初始化。如果您使用列表而不是IList,如下所示它工作。
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim myList As New List(Of Integer)
For x = 1 To 10
myList.Add(x)
Next
MsgBox(myList.Max())
End Sub
End Module
它工作正常,即使只有系統處於項目導入。
你必須確保你import System.Linq
,並添加System.Core.dll
爲你的項目的引用。
這是因爲Max
是System.Linq.Enumerable
類中定義的擴展方法。在System.Collections.Generic.IList(Of T)
接口中定義的是而不是。
因爲'List'沒有定義Max方法,所以我沒有看到代碼如何工作,沒有導入'System.Linq'。 –
也許這是隱式導入。舉例來說,vbc編譯器會爲你使用System.dll和System.Core.dll,但可能更多,但我沒有嘗試使用命令行明確引用它們。 –
僅供參考,我發現[這個SO問題](http://stackoverflow.com/questions/5094365/vb-net-2k8-how-to-make-all-imports-visible-within-a-class)哪描述哪些名稱空間在VB 2008/2010中隱式導入。它包含'System.Linq'命名空間。 –