字典<'K,'V>的类型扩展错误 [英] Type extension errors for Dictionary<'K, 'V>

查看:93
本文介绍了字典<'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

编辑

根据 F#spec(14.11 CLI方法的附加限制)


一些特定的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
  • $的类型 ty:等于 b $ b
  • x.GetHashCode()需要类型 ty:等于为静态类型 x

  • 新词典< A,B>()需要code> A:等于,因为任何不占用code的重载IEqualityComparer< T>

  • x.Equals(yobj) requires type ty : equality for the static type of x
  • x.GetHashCode() requires type ty : equality for the static type of x
  • new Dictionary<A,B>() requires A : equality, for any overload that does not take an IEqualityComparer<T>

这篇关于字典&lt;'K,'V&gt;的类型扩展错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆