VB.NET 扩展方法错误

发布于 2024-10-20 15:59:05 字数 652 浏览 3 评论 0原文

''' <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

使用

Dim buttonControl As New System.Windows.Forms.Button
Dim controls = buttonControl.ToList(Of System.Windows.Forms.Control)()

编译时错误(在最后一行)

扩展方法“公共函数” ToList() 作为 System.Collections.Generic.List(Of T)' '...Utils' 中定义的不是通用的 (或者没有自由类型参数)并且 所以不能有类型参数。

是das吗?

''' <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.Collections.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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终遇你 2024-10-27 15:59:05

试试这个:

<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

基本上你的返回类型是一个泛型(声明为 List (of T))。这里的函数声明做到了这一点,以便返回类型是正在扩展的类型的列表。

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.

玉环 2024-10-27 15:59:05

试试这个。

<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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文