枚举上的F#类约束 [英] F# type constraints on enums

查看:114
本文介绍了枚举上的F#类约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一个字符串到一个枚举来定义一个通用的转换运算符,我想像这样使用:

I'm trying to define a generic conversion operator from a string to an Enum, and I'd like to use it like this:

let day = asEnum<DayOfWeek>("Monday")

let asEnum<'a, 'b when 'a: (new : unit -> 'a) and 'a : struct and 'a :> ValueType and 'a : enum<'b>> text = 
    match Enum.TryParse<'a>(text)  with
    | true, value -> Some value
    | false, _ -> None

我只能这样使用:

    let day = asEnum<DayOfWeek,_>("Monday")

    let day:DayOfWeek option = asEnum("Monday")

如果我省略了'a:enum<'b> 类型约束,我可以按照我想要的,但如果有人没有指定类型,它将默认为 int ,我真的不喜欢,我'd喜欢它给出一个编译时间错误,就像我指定一个约束时一样。

If I omit the 'a : enum<'b> altogether from the type constraint, I can have it as I want, but then if someone doesn't specify the type it will default to int, which I really don't like, I'd prefer it to give a compile time error like it does when I specify a constraint

也许有一些技巧只是指定一个类型的参数,另一个是内在的?任何想法?

Maybe there's any trick to just specify one type parameter and have the other one infered? Any ideas?

推荐答案

这个怎么样?

let asEnum s :'a option when 'a:enum<'b> =
    match System.Enum.TryParse s with
    | true, v -> Some v
    | _ -> None

// works, but warns that type params shouldn't be given explicitly
asEnum<System.Reflection.BindingFlags,_> "DeclaredOnly"    
// also okay
(asEnum "DeclaredOnly" : System.Reflection.BindingFlags option)

这篇关于枚举上的F#类约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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