gpt4 book ai didi

.net - 扩展方法和类型约束

转载 作者:行者123 更新时间:2023-12-01 13:05:05 25 4
gpt4 key购买 nike

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

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

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

我错过了什么吗?有什么办法可以让我在这里做我想做的事吗??

提前致谢

最佳答案

Extension method '<methodname>' has type constraints that can never be satisfied.

我已阅读以下有关此错误的信息 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 [...]

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


哪种方式有意义。毕竟,想象一下您将如何调用您的扩展方法:

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

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

诚然,编译器可以通过让您明确声明它来推断出其他类型参数,à la values.ToDictionary(Of TKey)() , 但显然它不允许这样做。

关于.net - 扩展方法和类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3700621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com