如何使用VB.NET IList(Of T).Max

Ste*_*ven 1 .net vb.net ilist .net-3.5

如何在下面的示例中使用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()) 
Run Code Online (Sandbox Code Playgroud)

Ken*_*nde 5

您必须确保自己import System.Linq,并将其添加System.Core.dll为项目的参考.

这是因为MaxSystem.Linq.Enumerable类中定义的扩展方法.它没有System.Collections.Generic.IList(Of T)界面中定义.


Car*_*lla 5

调用myList.add时,您的代码会抛出System.NullReferenceException,因为它尚未初始化.如果您使用List而不是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
Run Code Online (Sandbox Code Playgroud)

即使在项目中仅导入System,它也能正常工作.