用数组键入测试模式

JDB*_*JDB 2 f# pattern-matching

我有一种情况,我交给一个对象,需要产生一个字符串.在大多数情况下,我可以调用它.ToString()并完成它(适用于字符串,数字,日期等)

这不起作用的一种情况是表示GUID的字节数组.在这种情况下,ToString()只需报告"System.Byte []".我正在尝试使用模式匹配来捕获字节数组,以便我可以自定义字符串化.但我无法弄清楚如何匹配字节数组(或实际上,任何数组),除了通过数组模式.GUID是16个字节长,我真的不希望有一个16个命名数组元素的模式.此外,使用数组模式会导致F#想要一个数组作为输入,而不是一个对象:

match value (* <-- obj *) with
| [|
    b1;  b2;  b3;  b4;
    b5;  b6;  b7;  b8;
    b9;  b10; b11; b12;
    b13; b14; b15; b16
  |] -> (* do some magic here later... *) b1.ToString()
| x -> x.ToString()
Run Code Online (Sandbox Code Playgroud)
> This expression was expected to have type obj but here has type 'a []
Run Code Online (Sandbox Code Playgroud)

我试图使用Type测试模式,但它会导致编译器错误(似乎有一个打开方括号的问题):

match value (* <-- obj *) with
| :? byte[] as guid -> (* do some magic here later... *) guid.ToString()
| x -> x.ToString()
Run Code Online (Sandbox Code Playgroud)
> Unexpected symbol '[' in pattern matching. Expected '->' or other token.
Run Code Online (Sandbox Code Playgroud)

关于模式匹配的F#文档似乎不包括数组类型测试,我没有通过Google找到任何适合我需求的内容.这里的语法是什么?

Lee*_*Lee 6

您可以使用:

match o with
| :? array<byte> as guid -> ...
Run Code Online (Sandbox Code Playgroud)

您还可以在类型名称周围加上括号:

 match o with
    | :? (byte[]) as guid -> ...
Run Code Online (Sandbox Code Playgroud)

要么

 match o with
    | :? (byte array) as guid -> ...
Run Code Online (Sandbox Code Playgroud)