字典<'K,'V>的类型扩展错误 [英] Type extension errors for Dictionary<'K, 'V>
问题描述
以下类型的扩展名
module Dict =
open System.Collections.Generic
type Dictionary<'K, 'V> with
member this.Difference(that:Dictionary<'K, 'T>) =
let dict = Dictionary()
for KeyValue(k, v) in this do
if not (that.ContainsKey(k)) then
dict.Add(k, v)
dict
给出错误:
签名和实现不兼容,因为类型参数TKey的声明需要格式为TKey:相等性的限制条件
The signature and implementation are not compatible because the declaration of the type parameter 'TKey' requires a constraint of the form 'TKey : equality
但是当我添加约束时会给出错误:
But when I add the constraint it gives the error:
此类型扩展名的声明类型参数与原始类型'Dictionary< ,>'
这是非常神秘的,因为以下类型的扩展名没有约束和作用。
This is especially mysterious because the following type extension doesn't have the constraint and works.
type Dictionary<'K, 'V> with
member this.TryGet(key) =
match this.TryGetValue(key) with
| true, v -> Some v
| _ -> None
现在我有奇怪的想法:只有在访问某些成员时,才需要约束? / p>
Now I'm having weird thoughts: is the constraint required only when certain members are accessed?
推荐答案
module Dict =
open System.Collections.Generic
type Dictionary<'K, 'V> with
member this.Difference(that:Dictionary<'K, 'T>) =
let dict = Dictionary(this.Comparer)
for KeyValue(k, v) in this do
if not (that.ContainsKey(k)) then
dict.Add(k, v)
dict
编辑:
一些特定的CLI方法和类型由F#特别处理,因为它们在F#编程中很常见,导致非常难以发现的错误。对于以下结构的每次使用,F#编译器都会施加额外的临时约束:
Some specific CLI methods and types are treated specially by F#, because they are common in F# programming and cause extremely difficult-to-find bugs. For each use of the following constructs, the F# compiler imposes additional ad hoc constraints:
-
x.Equals(yobj )
要求静态类型x
$的类型 -
x.GetHashCode()
需要类型ty:等于
为静态类型x
-
新词典< A,B>()
需要code> A:等于,因为任何不占用code的重载IEqualityComparer< T>
ty:等于
b $ b x.Equals(yobj)
requires typety : equality
for the static type ofx
x.GetHashCode()
requires typety : equality
for the static type ofx
new Dictionary<A,B>()
requiresA : equality
, for any overload that does not take anIEqualityComparer<T>
这篇关于字典<'K,'V>的类型扩展错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!