扩展方法和类型约束

时间:2010-09-13 13:03:52

标签: .net vb.net generics extension-methods

我开始使用扩展方法,我遇到了这个问题: 在下一个场景中,我得到了一个:

“扩展方法具有永远无法满足的类型约束”

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 Integer)替换IKeyedObject(Of k),它就有用了

  <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

我错过了什么吗?我能以任何方式做我想做的事吗?

提前致谢

1 个答案:

答案 0 :(得分:4)

  

扩展方法'&lt; methodname&gt;'具有永远无法满足的类型约束。

我已阅读以下有关此错误的信息on MSDN

  

因为该方法是一种扩展方法,所以编译器必须能够仅根据方法声明中的第一个参数确定方法扩展的数据类型。 ]

在您的情况下,编译器必须能够从参数TKey中推导出TValuel,这是不可能的。因此编译器警告。


哪种有道理。毕竟,想象一下你将如何调用你的扩展方法:

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

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

不可否认,编译器可以通过让你明确说明它来推断出其他类型参数,但是显然它不允许这样做。

相关问题