Extension method and type constraints
I am starting to play with extension methods and i came across with this problem: In the next scenario i get a:
"extension method has a type constraint that can never be satisfied"
Public Interface IKeyedObject(Of TKey As IEquatable(Of TKey))
ReadOnly Property InstanceKey() As TK开发者_高级运维ey
End Interface
<Extension()> _
Public Function ToDictionary(Of TKey As IEquatable(Of TKey), tValue As IKeyedObject(Of TKey))(ByVal l As IEnumerable(Of tValue)) As IDictionary(Of TKey, tValue)
'code
End Function
But it works if i replace IKeyedObject(Of k) with IKeyedObject(Of Integer)
<Extension()> _
Public Function ToDictionary(Of TKey As IEquatable(Of TKey), tValue As IKeyedObject(Of TKey))(ByVal l As IEnumerable(Of tValue)) As IDictionary(Of TKey, tValue)
'code
End Function
Am i missing something? is any way i can do what i want here??
Thanks in advance
Extension method '<methodname>' has type constraints that can never be satisfied.
I've read the following about this error on MSDN:
Because the method is an extension method, the compiler must be able to determine the data type or types that the method extends based only on the first parameter in the method declaration [...]
In your case, the compiler would have to be able to deduce both TKey
and TValue
from parameter l
, which is not possible. Thus the compiler warning.
Which sort-of makes sense. After all, imagine how you're going to call your extension method:
Dim values As IEnumerable(Of TValue) = ...
Dim dictionary As IDictionary(Of ?, TValue) = values.ToDictionary()
' ^ '
' where does the compiler get this type from? '
Admittedly, the compiler could deduce the other type parameter by letting you state it explicitly, à la values.ToDictionary(Of TKey)()
, but apparently it doesn't allow this.
精彩评论