简体   繁体   English

f#将字符串解析为颜色

[英]f# parsing string to color

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}

I am trying to parse a textbox.text into a color. 我正在尝试将textbox.text解析为一种颜色。 From this code i get the error: 从这段代码我得到错误:

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

Quite new to F# and not to sure about the syntax. 对于F#来说还很新,并且不确定语法。 The error comes at 错误出现在

"Color = txtBoxVal4"

System.Enum.Parse returns an obj type that you need to cast to the enum type. System.Enum.Parse返回需要转换为枚举类型的obj类型。 You can do that using :?> or downcast . 您可以使用:?>downcast做到这一点。 In your case the type is known so you can use downcast . 在您的情况下,类型是已知的,因此您可以使用downcast

See the Casting and Conversions docs for more. 有关更多信息,请参见“ 投放和转化”文档。

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

A wrapper function for Enum.Parse could make good use of the enum constraint and eliminate the need for unboxing at the call site. 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM