F# System.Array[]与F中的浮点[]不兼容#
我需要调用一个函数,该函数将F# System.Array[]与F中的浮点[]不兼容#,f#,polymorphism,F#,Polymorphism,我需要调用一个函数,该函数将System.Array[]作为F#中的一个参数。(该函数位于库中)。 我需要传递类型为float[][]的参数,但编译器拒绝编译。为了复制这个问题,我编写了以下代码 let x : float [] [] = Array.init 2 (fun x -> Array.zeroCreate 3) x :> System.Array;; // This is OK val x : float [] [] = [|[|0.0; 0.0; 0.0|]; [|0
System.Array[]
作为F#中的一个参数。(该函数位于库中)。
我需要传递类型为float[][]
的参数,但编译器拒绝编译。为了复制这个问题,我编写了以下代码
let x : float [] [] = Array.init 2 (fun x -> Array.zeroCreate 3)
x :> System.Array;; // This is OK
val x : float [] [] = [|[|0.0; 0.0; 0.0|]; [|0.0; 0.0; 0.0|]|]
> x :> System.Array [];; //Error
x :> System.Array [];;
^^^^^^^^^^^^^^^^^^^^
stdin(14,1): warning FS0059: The type 'System.Array []' does not have any proper subtypes and need not be used as the target of a static coercion
x :> System.Array [];;
^^^^^^^^^^^^^^^^^^^^
stdin(14,1): error FS0193: Type constraint mismatch. The type
float [] []
is not compatible with type
System.Array []
The type 'System.Array' does not match the type 'float []'
我怎样才能解决这个问题
提前感谢。您可以这样做:
let x : float [] [] = Array.init 2 (fun x -> Array.zeroCreate 3)
let toArray (xs : #System.Array []) =
Array.map (fun x -> x :> System.Array) xs
let x' : System.Array [] = toArray x
您可以这样做:
let x : float [] [] = Array.init 2 (fun x -> Array.zeroCreate 3)
let toArray (xs : #System.Array []) =
Array.map (fun x -> x :> System.Array) xs
let x' : System.Array [] = toArray x
当
's:>'t
时,将's[]
视为't[]
的能力会使.NET类型的系统不健全(这可能是由于Java做了同样的事情)。不幸的是,C#遵循.NET允许这样做
因为它是一个.NET运行时功能,所以您也可以在F#中通过装箱和拆箱来实现:
let x : float[][] = Array.init 2 (fun x -> Array.zeroCreate 3)
let x' = (box x) :?> System.Array[]
这避免了在Ramon的解决方案中映射每个元素的开销
查看为什么这使得.NET类型系统不健全,考虑如下:
x'.[0] <- upcast [| "test" |] // System.ArrayTypeMismatchException
x.[0]当's:>'t
使.NET类型系统不健全时,将's[]
视为't[]
的能力(可能是因为Java做了同样的事情)。不幸的是,C#遵循.NET允许这样做
因为它是一个.NET运行时功能,所以您也可以在F#中通过装箱和拆箱来实现:
let x : float[][] = Array.init 2 (fun x -> Array.zeroCreate 3)
let x' = (box x) :?> System.Array[]
这避免了在Ramon的解决方案中映射每个元素的开销
查看为什么这使得.NET类型系统不健全,考虑如下:
x'.[0] <- upcast [| "test" |] // System.ArrayTypeMismatchException
x.[0]这正是我刚才想到的。我现在就用它。但我仍然想知道是否有一种直接施放的方法。不是在F中,是在C中(其中一个-variance)。这正是我刚才想到的。我现在就用它。但我仍然想知道是否有一种方法可以直接使用它。不是用F#,是用C#(一种-variance)。谢谢你指出这个问题。当我第一次了解到我可以在Java和C#中实现这一点时,我实际上被这种行为弄糊涂了,事实证明,数组类型在这两种语言中都是协变的。事实证明,F#只是选择回到正常意义上的继承。感谢您指出这个问题。当我第一次了解到我可以在Java和C#中实现这一点时,我实际上被这种行为弄糊涂了,事实证明,数组类型在这两种语言中都是协变的。事实证明,F#只是选择回到正常意义上的继承。