代码之家  ›  专栏  ›  技术社区  ›  Binary Worrier

一种推广方法上具有一般约束的奇性

  •  2
  • Binary Worrier  · 技术社区  · 17 年前

    bug in the Vb.net compiler ?)

    类型约束,这些约束永远不能被删除

    下面是一个显示相同问题的简单示例。旧的静态版本(工作正常)后面跟着扩展方法

    Public Class MyStaticClass
        Public Shared Sub AddIfUnqiue(Of T, L As {List(Of T)})(ByVal this As L, ByVal item As T)
            If this.IndexOf(item) < 0 Then
                this.Add(item)
            End If
        End Sub
    End Class
    
    Module UtilityExtensions
        <Extension()> _
        Sub AddIfUnqiue(Of T, L As {List(Of T)})(ByVal this As L, ByVal item As T)
        'ERROR: Extension method 'AddIfUnqiue' has type constraints that can never be satisfied'
            If this.IndexOf(item) < 0 Then
                this.Add(item)
            End If
        End Sub 
    End Module
    

    C#中的等效代码没有问题,只是Vb的问题。

    public static void AddIfUnique<T, L>(this L myList, T item) where L : List<T>
    {
        if (myList.IndexOf(item) < 0)
            myList.Add(item);
    }
    

    有人知道为什么这样不行吗? 这很可能是我的Vb限制(我更喜欢c),但我看不出我做错了什么。

    谢谢

    2 回复  |  直到 9 年前
        1
  •  3
  •   Meta-Knight    17 年前

    这不是一个bug,解释了它不能编译的原因 here .

    因为该方法是一个扩展 方法,编译器必须能够 该方法仅基于 方法中的第一个参数 宣言。

    <Extension()> _
    Sub AddIfUnique(Of T)(ByVal this As List(Of T), ByVal item As T)
        ...
    End Sub
    
        2
  •  1
  •   P. Wolff    9 年前

    我得说这是一只虫子。

    有趣的是,同样的标题不仅在C#(如您所述)中可以正常工作,在VB中也可以- 如果

    关于“扩展方法仅仅是语法上的糖分”的讨论太多了