8

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

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,我真的不喜欢,我希望它给出一个编译时间错误,就像我指定约束时一样

也许只指定一个类型参数并推断另一个类型参数有什么技巧?有任何想法吗?

4

4 回答 4

4

不幸的是,为了增加约束,您似乎必须将其全部拼写出来:(正如 kvb 指出的那样,您可以通过在尖括号外TryParse添加约束来避免重复约束)'T : enum<int>

这也有效:

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

如果基础类型不是,这会产生编译时错误int

type ByteEnum =
  | None = 0uy

asEnum<ByteEnum> "None" //ERROR: The type 'int' does not match the type 'byte'
于 2013-02-27T15:02:08.747 回答
3

这个怎么样?

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)
于 2013-02-27T15:49:28.520 回答
1

3年后的小更新^_^

使用此字符串扩展名将字符串转换为枚举

type System.String with
        /// Strongly-typed shortcut for Enum.TryParse(). 
        member this.ToEnum<'a when 'a :> System.Enum and 'a : struct and 'a : (new: unit -> 'a)> () =
            let ok, v = System.Enum.TryParse<'a>(this, true)
            if ok then Some v else None    

小心你的枚举声明。

type failingEnum =
            | FirstValue
            | SecondValue
            | AnotherValue

type compliantEnum =
            | FirstValue = 0
            | SecondValue = 1
            | AnotherValue = 2

然后

let x = "whatever".ToEnum<failingEnum>(); 
//- will give error failingEnum is not compatible with the type System.Enum

let x = "whatever".ToEnum<compliantEnum>(); 
//- will succeed !
于 2016-01-27T07:40:46.930 回答
0

我尝试的另一件事是:

type AsEnum = 

    static member Get<'a, 'b when 'a: (new : unit -> 'a) and 'a : struct and 'a :> ValueType and 'a : enum<int>> (text:string) =

        match Enum.TryParse<'a>(text) with
        | true, value -> Some value
        | _ -> None

    static member Get<'a, 'b when 'a: (new : unit -> 'a) and 'a : struct and 'a :> ValueType and 'a : enum<int64>> (text:string) =

        match Enum.TryParse<'a>(text) with
        | true, value -> Some value
        | _ -> None

let a = AsEnum.Get<BindingFlags>.Get "DeclaredOnly"   

尝试查看是否可以让编译器推断要调用哪个重载,但如果失败并出现歧义错误

于 2013-02-27T16:28:48.503 回答