扩展方法和类型约束

3
我开始尝试使用扩展方法,并遇到了这个问题: 在下面的场景中,我会得到一个:
"扩展方法具有永远无法满足的类型约束"
Public Interface IKeyedObject(Of TKey As IEquatable(Of TKey))
    ReadOnly Property InstanceKey() As TKey 
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

如果我将 IKeyedObject(Of k) 替换为 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

我有点不明白,有没有办法在这里做我想做的事情?谢谢。

你的第二段代码也无法编译,修复你的代码。 - Hans Passant
1个回答

4

扩展方法'<methodname>'的类型约束永远无法满足。

我在MSDN上读到了关于这个错误的以下内容:

由于该方法是扩展方法,编译器必须仅基于方法声明中的第一个参数来确定方法扩展的数据类型或数据类型[...]

在您的情况下,编译器必须能够从参数l中推断出TKeyTValue,这是不可能的。因此会出现编译器警告。


这有点说得通。毕竟,想象一下如何调用您的扩展方法:

Dim values As IEnumerable(Of TValue) = ...

Dim dictionary As IDictionary(Of ?, TValue) = values.ToDictionary()
'                                ^                                            '
'                                where does the compiler get this type from?  '

诚然,编译器可以通过让您明确声明另一个类型参数来推断它,例如values.ToDictionary(Of TKey)(),但显然它不允许这样做。

话虽如此,我可以想象,一旦你实现了接口和扩展方法,你迟早会不可避免地遇到导致编译器错误的问题。(我很好奇这个说法是否正确;我也可能是错的。) - stakx - no longer contributing
公共函数 ToDictionary(tValue As IKeyedObject(Of Integer))(ByVal l As IEnumerable(Of tValue)) As IDictionary(Of Integer, tValue)等等,对于每种类型的键,然后当我使用:Values.Todictionary() 我可以做:Values.Todictionary(Of Integer),对于每个定义的类型。 - Burnsys

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接