代码之家  ›  专栏  ›  技术社区  ›  pblasucci

如何实现与Dictionary.TryGetValue相同的行为

  •  7
  • pblasucci  · 技术社区  · 16 年前

    那么,给出下面的代码

    type MyClass () =
      let items = Dictionary<string,int>()
      do 
        items.Add ("one",1)
        items.Add ("two",2)
        items.Add ("three",3)
      member this.TryGetValue (key,value) =
        items.TrygetValue (key,value)
    let c = MyClass () 
    
    let d = Dictionary<string,int> ()
    d.Add ("one",1)
    d.Add ("two",2)
    d.Add ("three",3)
    

    以及以下测试代码

    let r1,v1 = d.TryGetValue "one"
    let r2,v2 = c.TryGetValue "one"
    

    如果不清楚请告诉我。

    2 回复  |  直到 16 年前
        1
  •  8
  •   Brian    16 年前

    TryGetValue 有一个out参数,所以您需要在F#中执行相同的操作(通过 byref OutAttribute ):

    open System.Runtime.InteropServices 
    type MyDict<'K,'V when 'K : equality>() =  // '
        let d = new System.Collections.Generic.Dictionary<'K,'V>()
        member this.TryGetValue(k : 'K, [<Out>] v: byref<'V>) =
            let ok, r = d.TryGetValue(k)
            if ok then
                v <- r
            ok            
    
    let d = new MyDict<string,int>()
    let ok, i = d.TryGetValue("hi")
    let mutable j = 0
    let ok2 = d.TryGetValue("hi", &j)
    

        2
  •  4
  •   Stephen Swensen    15 年前

    就我个人而言,我从来都不喜欢 bool TryXXX(stringToParseOrKeyToLookup, out parsedInputOrLookupValue_DefaultIfParseFailsOrLookupNotFound) Some / None 图案会很完美(比如 Seq.tryFind

    type MyClass () =
      let items = System.Collections.Generic.Dictionary<string,int>()
      do 
        items.Add ("one",1)
        items.Add ("two",2)
        items.Add ("three",3)
      member this.TryGetValue (key) =
        match items.TryGetValue(key) with
            | (true, v) -> Some(v)
            | _ -> None
    
    let c = MyClass()
    
    let printKeyValue key =
        match c.TryGetValue(key) with
        | Some(value) -> printfn "key=%s, value=%i" key value
        | None -> printfn "key=%s, value=None" key
    
    //> printKeyValue "three";;
    //key=three, value=3
    //val it : unit = ()
    //> printKeyValue "four";;
    //key=four, value=None
    //val it : unit = ()