f#将字符串解析为颜色

时间:2014-01-20 12:39:26

标签: parsing colors f#

type circle = { X : int; Y : int; Diameter : int; Color : Color}
let mutable clickedCircle = { X = 0; Y = 0; Diameter = 0; Color = Color.White}

let txtBoxVal4 = System.Enum.Parse(typeof<Color>,txtBox2.Text)
clickedCircle <- {X = txtBoxVal2; Y = txtBoxVal3; Diameter = txtBoxVal1; Color = txtBoxVal4}

我正在尝试将textbox.text解析为一种颜色。从这段代码我得到错误:

Error   1   This expression was expected to have type
Color    
but here has type
obj 

F#的新手并不确定语法。错误发生在

"Color = txtBoxVal4"

2 个答案:

答案 0 :(得分:1)

System.Enum.Parse返回您需要强制转换为枚举类型的obj类型。您可以使用:?>downcast执行此操作。在您的情况下,类型已知,因此您可以使用downcast

有关详情,请参阅Casting and Conversions文档。

clickedCircle <- {X = txtBoxVal2; Y = txtBoxVal3; Diameter = txtBoxVal1; Color = downcast txtBoxVal4}

答案 1 :(得分:1)

Enum.Parse的包装函数可以充分利用enum约束,无需在呼叫站点进行拆箱。

module Enum =
  let parse<'T, 'U when 'T : enum<'U>> value = Enum.Parse(typeof<'T>, value) :?> 'T

let color = Enum.parse "Black"