我能否获得静态解析类型参数的类型?

5

比如我有这样的一段代码, 它不能编译,但你可以看到我的意图。我试过各种搜索方式,但都没有找到答案。这个能做到吗?

let inline read (s:string) : ^x =
    let parsed = (^x : (static member ofString: string -> ^x option) (s))

    // this is the bit I'm not sure how do to. This doesn't compile.
    // I'm trying to determine what the statically chosen type for ^x is.
    let t = typeof<^x>

    match parsed with
    | Some y -> y
    | None -> failwithf "can't parse %s into %s" s (t.Name)
1个回答

10

这个很好用,而且你可以在静态解析参数上使用typeof - 问题在于解析器无法处理<^,因为它也可以被解析为运算符。

你可以通过在^x周围添加空格来轻松解决此问题:

let t = typeof< ^x >

3
啊,这真让人沮丧!我花了足够长的时间做研究,然后去Stack Overflow上找答案,结果发现我只需要一个空格! - Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接