2

是否可以将类型限制为支持 null 的结构或引用类型?类似于此函数的假设约束:

let getOrDefault<'T when ('T : struct) or ('T : null)> (d: IDictionary<_, 'T>) key =
  match d.TryGetValue(key) with
  | true, v -> v
  | _ -> Unchecked.defaultof<'T>

该函数不应与 F# 类型一起使用,除非用[<AllowNullLiteral>].

4

1 回答 1

3

我认为你不能or在两个约束之间放置一个。通常当我需要像constraint1或constraint2或...或constraintN这样的东西时,我所做的是创建重载:

open System.Collections.Generic

// unconstrained function
let getOrDefaultG (d: IDictionary< _ , 'T>) key =
  match d.TryGetValue(key) with
  | true, v -> v
  | _ -> Unchecked.defaultof<'T>

// individually constrained
let getOrDefaultS<'K,'T when 'T :struct> (d:IDictionary<'K,'T>) = getOrDefaultG d
let getOrDefaultN<'K,'T when 'T :null  > (d:IDictionary<'K,'T>) = getOrDefaultG d

// overloads
type GetOrDefault = GetOrDefault with
    static member ($) (GetOrDefault, d) = fun dummyArg        -> getOrDefaultS d
    static member ($) (GetOrDefault, d) = fun (dummyArg:unit) -> getOrDefaultN d

// the desired function
let inline getOrDefault d key = (GetOrDefault $ d) () key

注意: dummyArg 是我用来创建两个不同签名并使其编译的技巧。

于 2012-08-07T06:11:00.420 回答