VB.NET Extension methods error
''' <summary>
''' Transforms an item to a list of single element containing this item.
''' '</summary>
<Extension()> _
Public Function ToList(Of T)(ByVal item As T) As List(Of T)
Dim tList As New List(Of T)
tList.Add(item)
Return tList
End Function
usage
Dim buttonControl As New System.Windows.Forms.Button
Dim controls = buttonControl.ToList(Of System.Windows.Forms.Control)()
compile time error (on the last line)
Extension method 'Public Function ToList() As System.Collecti开发者_JAVA百科ons.Generic.List(Of T)' defined in '...Utils' is not generic (or has no free type parameters) and so cannot have type arguments.
Was is das?
Try this:
<Extension()> _
Public Function ToList(Of TItem, TList As {New, List(Of TItem)})(ByVal item As TItem) As TList
Dim tList As New TList
tList.Add(item)
Return tList
End Function
Basically your return type was a generic (declared as List (of T)). The function decaration here does it so that the return type is a list of the type that is being extended.
Try this.
<Extension()>
Public Function ToList(Of T)(ByVal Item As Object) As List(Of T)
Dim tlist1 As New List(Of T)
tlist1.Add(Item)
Return tlist1
End Function
精彩评论