2009-09-02 161 views
2

我必須錯在這裏做一些奇怪的行爲(因爲真的,什麼是我絆倒在另一bug in the Vb.net compiler機會?)與擴展方法泛型約束

我在.NET 2.0 Vb的靜態泛型函數代碼,我認爲這是一次「升級」它是一個擴展方法,但是編譯器與

擴展方法「AddIfUnqiue」有 型約束條件永遠無法滿足 抱怨。

這是一個簡單的例子,顯示相同的問題。舊的靜態版本(其中正常工作),其次是擴展方法

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#),但我看不出我做錯了什麼。

感謝,

回答

3

這不是一個錯誤,它爲什麼不編譯的原因解釋here

因爲該方法是一個擴展 方法,編譯器必須能夠 確定數據類型或 方法延伸僅基於該方法 申報 第一個參數類型。

在你的情況,你只需要你的代碼改成這樣:

<Extension()> _ 
Sub AddIfUnique(Of T)(ByVal this As List(Of T), ByVal item As T) 
    ... 
End Sub 
+0

你確實是閃亮盔甲的元騎士。非常感謝 :) – 2009-09-03 08:27:04

0

我會說這是一個錯誤。

有趣的事情,同樣的頭不僅在C#中工作得很好(因爲你已經說明),但在VB以及 - 如果您刪除<擴展>屬性。

這麼多關於「擴展方法僅僅是語法糖」。