扩展方法和类型约束
我开始使用扩展方法,遇到了这个问题: 在下一个场景中,我得到一个:
“扩展方法具有永远无法满足的类型约束”
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
我错过了什么吗?有什么办法我可以在这里做我想做的事吗?
提前致谢
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 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已阅读以下有关此错误的内容 MSDN:
在您的情况下,编译器必须能够从参数
l
推断出TKey
和TValue
,这是不可能的。因此编译器会发出警告。哪一种是有道理的。毕竟,想象一下您将如何调用扩展方法:
诚然,编译器可以通过让您显式声明另一个类型参数来推断它,就像
values.ToDictionary(Of TKey)()
,但显然它不允许这样做。I've read the following about this error on MSDN:
In your case, the compiler would have to be able to deduce both
TKey
andTValue
from parameterl
, 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:
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.