数据继承与字典

时间:2014-10-08 20:14:37

标签: .net f# f#-3.0

我有一条消息传递了包含一些状态值的属性包(.Net字典)。现在增加了范围,所以也可以有一个儿童财产包。我正在尝试使用一个干净的方法,首先使用子元素从属性包中查找状态参数,否则返回到父属性包。

我有一个有效的解决方案,但似乎这应该更好,更清晰。你能推荐一个改进吗?

let private _fetchParameter (parameter : Parameters) (name : string) =
   let success, value = parameter.TryGetValue(name)
   match success with
   | true -> Some(value) 
   | false -> None

let internal _deepFetchParameter (child: Parameters) (parent: Parameters) (name : string) =
    let foundValue = 
        match _fetchParameter child name with
        | Some x -> Some x
        | None -> _fetchParameter parent name 

    match foundValue with
    | Some x -> x
    | None -> invalidArg name (sprintf "Could not find parameter named %s in parameters or event." name)

// an example usage
let configSetting1 = _deepFetchParameter child parent "ConfigSetting1"

很少有小调:

  • 我意识到抛出异常不是惯用的F#,但这是与某些标准的.net交互,抛出异常就是这种情况下的正确行为。 (应用程序的其余部分会抛出异常,我希望保持一致)。
  • 我相信可能有更好的方法来表示F#中的数据继承/数据范围,但这是我在这个网站上提出的另一个问题。我对这个问题的意图是提高我对F#和功能设计的理解。
  • 参数是一种类型,它是标准.Net dictionary<T,U>的别名,类型为<string, string>
  • 有关更改或抽象数据存储的建议很好,只要您可以建议合并字典的方法。

1 个答案:

答案 0 :(得分:2)

我会对此采取行动:

let internal _deepFetchParameter (child: Parameters) (parent: Parameters) (name : string) =
    let childFetch = _fetchParameter child
    let parentFetch = _fetchParameter parent

    match (childFetch name),(parentFetch name) with
    | Some(x), _ -> x
    | None, Some(x) -> x
    | _ -> invalidArg name (sprintf "Could not find parameter named %s in parameters or event." name)