Rob*_*lls 1 arrays f# discriminated-union
如果我有不同类型数组的区别联合,我怎么能将它们转换为'实际'类型?
type ItemStuff =
| Colors of string[]
| Sizes of int[]
let foo = Sizes [|1;2;3|]
Run Code Online (Sandbox Code Playgroud)
运行上面的内容后,当我得到foo的值时,我看到:
val foo : ItemStuff = Sizes [|1;2;3|]
Run Code Online (Sandbox Code Playgroud)
如何从foo获取实际的int数组?我只是缺少一些允许我访问类似的语法
foo.[2]吗?我不能通过foo枚举所以我无法使用地图.我可以为ItemStuff编写一个成员,为我返回的每个不同类型的数组返回一个正确类型的数组,但这似乎不正确?
我最好的方法是什么?
这就是我最终做的事情.关于更好的方法的任何想法?
type ItemProp =
| Colors of string[]
| Sizes of int[]
| Quants of int[]
member this.GetColors() =
match this with
| Colors (stringArray) ->
stringArray
| _ -> null
member this.GetIntArr() =
match this with
| Sizes (intArray) | Quants (intArray) ->
intArray
|_ -> null
foo.GetIntArr()
Run Code Online (Sandbox Code Playgroud)
如何从foo获取实际的int数组?
这是实际问题,因为foo据说只有类型ItemStuff.因此它根本不必包含Sizes-value - 它也可以是一个Colors.
因此你的程序必须在这里决定
let getIntArray = function
| Sizes arr -> arr
| Colors _ -> failwith "Given value doesn't contain an int array`
Run Code Online (Sandbox Code Playgroud)
getIntArray foo将正常工作,但getIntArray (Colors [||])将失败,但从类型级别都是有效的.
请注意,如果您完全确定操作将成功,则可以直接使用模式匹配:
let getIntArray (Sizes arr) = arr
Run Code Online (Sandbox Code Playgroud)