打印已区分联盟的案例标识符 [英] Print case-identifier of discriminated union

查看:92
本文介绍了打印已区分联盟的案例标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Option类型:

type Option<'a> =
    | Some of 'a
    | None

    override x.ToString() = sprintf "%A" x

printf "%A" None // "None"
printf "%A" (Some 1) // "Some 1"

应该在一个函数中打印Some 1,但是在另一个函数中,我要打印其大小写标识符,即Some(放弃"1"值).我该怎么办?

Supposedly, in a function I want to print Some 1, but in another function I want to print its case-identifier, i.e. Some (discard the " 1" value). How can I do it?

推荐答案

如果您想要通用的方法而不是为每种类型实现成员,则可以使用反射:

If you want a generic way of doing it rather than implement a member for each of your types, you can use reflection for that:

open Microsoft.FSharp.Reflection

let caseLabel<'t> (x: 't) = 
    let typ = typeof<'t>
    if FSharpType.IsUnion(typ) 
        then
            let case, _ = FSharpValue.GetUnionFields(x, typ)
            Some case.Name
        else
            None

这篇关于打印已区分联盟的案例标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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